Created
May 30, 2011 23:50
-
-
Save juandopazo/999644 to your computer and use it in GitHub Desktop.
Math.random()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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