Many times I find myself writing code which involves finding a random number in a given range. Often times that number needs to be an integer. Since this is such a common task, I figured I would share a brief snippet of code with you all:

function random(min, max, round) {
  var argc = arguments.length;
  if(argc == 2 && typeof max == "boolean") {
    round = max;
    max = min;
    min = 0;
  }
  else if(argc == 1) {
    if(typeof min == "boolean") {
      round = min;
      max = 1;
    }
    else {
      max = min;
    }
    min = 0;
  }
  else {
    min = min || 0;
    max = max == null ? 1 : max;
  }
  min = min + (Math.random() * (max - min));
  return round ? Math.round(min) : min;
}

The above function can take zero to three arguments. You can use the function in the following ways:

  • random()
  • random(max)
  • random(round)
  • random(min, max)
  • random(max, round)
  • random(min, max, round)

If min is not specified, 0 is used as the minimum value.  If max is not specified, 1 is used as the maximum value.  If round is not specified, the returned value will not be rounded.

It is important to remember that the number entered as max will never be generated while round evaluates to false (which is the default). On the other hand, if you do specify round as true, the random number that is generated will be within the given range allowing for either min or max to be returned.

Although the code above may look length for such a simple function, the Google Closure Compiler minified version is only 202 bytes and can be downloaded here if you so choose. Of course, you can use your own version of the function which works in the exact way that you like. I am simply supplying this as a generic solution in case you want to be able to use any of the aforementioned ways to generate random numbers. Have fun!!!

Categories: BlogJavaScriptJScript

Leave a Reply

Your email address will not be published. Required fields are marked *