HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Normalized random position generator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
normalizedrandompositiongenerator

Problem

I place various divs on screen by adding random x and y positions successively normalized with this function. My question is, how well is it written? Can I improve it? If so, then how?

I am worried not only about the coding style but also performance since I'm using multiple Math.random()s.

function normalize(n) {
        var x = 0, i = 0;
        while (i < n) {
            x += Math.random();
            i++;
        }
        return (x / n);
    }

Solution

With totally zero context of what's going on and I'm not a math person, why "normalize"? What does "normalize" mean? As a front-end developer, normalize.css comes into mind, but it's not related to CSS. So I'm clueless. If you can give a better name, that would be great.

Also, a more compact way to write this is using a for loop

function normalize(n) {
  for(var x = 0, i = 0; i < n; i++){
    x += Math.random();
  }
  return (x / n);
}

Code Snippets

function normalize(n) {
  for(var x = 0, i = 0; i < n; i++){
    x += Math.random();
  }
  return (x / n);
}

Context

StackExchange Code Review Q#119837, answer score: 2

Revisions (0)

No revisions yet.