Skip to content

Instantly share code, notes, and snippets.

@mediaupstream
Created September 20, 2011 19:35
Show Gist options
  • Select an option

  • Save mediaupstream/1230098 to your computer and use it in GitHub Desktop.

Select an option

Save mediaupstream/1230098 to your computer and use it in GitHub Desktop.
Random numbers, 3 ways - a Javascript Snippet.
/**
* Random numbers, 3 ways. Usage:
* - random() : returns a random integer
* - random(30) : returns a random integer from 0 to 30
* - random(20, 50) : returns a random integer from 20 to 50
*/
var random = function() {
var f = Math.floor, r = Math.random, a = arguments;
switch(a.length){
case 0: return f(r()); break;
case 1: return f(r() * (a[0] + 1));break;
case 2: return f(r() * (a[1] - a[0] + 1)) + a[0];break;
}
};
@mediaupstream

Copy link
Copy Markdown
Author

maybe do a check on the argument type to see if it's float or decimal and toggle the Math.floor on/off accordingly...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment