Skip to content

Instantly share code, notes, and snippets.

@juandopazo
Created May 30, 2011 23:50
Show Gist options
  • Save juandopazo/999644 to your computer and use it in GitHub Desktop.
Save juandopazo/999644 to your computer and use it in GitHub Desktop.
Math.random()
/*
It has always bugged me that every other language except Java returns an integer and JavaScript returns [0,1).
So, how about standarizing this?
*/
(function () {
var oldRandom = Math.random;
Object.defineProperty(Math, 'random', {
value: function random(n) {
return typeof n === 'undefined' ? oldRandom() :
typeof n === 'number' && Math.abs(n) <= Number.MAX_INTEGER ? Math.floor(oldRandom() * Math.floor(n)) :
NaN;
},
configurable: true,
writable: true
});
}());
// Or at least...
Object.defineProperty(Math, 'randomInt', {
value: function randomInt(n) {
if (typeof n === 'undefined') {
n = Number.MAX_INTEGER;
}
return typeof n === 'number' && Math.abs(n) <= Number.MAX_INTEGER ? Math.floor(Math.random() * Math.floor(n)) : NaN;
},
configurable: true,
writable: true
});
// Another proposal from @joseanpg Twitter
(function () {
function isNumberInIntRange(n) { return typeof n === 'number' && Math.abs(n) <= Number.MAX_INTEGER }
Object.defineProperty(Math, 'randomInt', {
value: function randomInt(a, b) {
if (typeof b === 'undefined') {
b = typeof a === 'undefined' ? Number.MAX_INTEGER : a;
a = 0;
} else if (typeof a === 'undefined') {
a = 0;
}
return isNumberInIntRange(a) && isNumberInIntRange(b) ? Math.floor(Math.random() * Math.floor(b)) + a : NaN;
},
configurable: true,
writable: true
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment