-
-
Save eAmin/42a67cf3cc98169ca9bd0a4e6f17197d to your computer and use it in GitHub Desktop.
Pseudorandom number generator based on crypto.randomBytes
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
var crypto = require('crypto') | |
, rrange = 4294967296; | |
/** | |
* Return an integer, pseudo-random number in the range [0, 2^32). | |
*/ | |
var nextInt = function() { | |
return crypto.randomBytes(4).readUInt32BE(0); | |
}; | |
/** | |
* Return a floating-point, pseudo-random number in the range [0, 1). | |
*/ | |
var rand = function() { | |
return nextInt() / rrange; | |
}; | |
/** | |
* Return an integer, pseudo-random number in the range [min, max]. | |
*/ | |
var randInt = function(min, max) { | |
if (typeof min === 'undefined') { | |
return nextInt(); | |
} | |
if (typeof max === 'undefined') { | |
max = min; | |
min = 0; | |
} | |
return min + Math.floor(rand() * (max - min + 1)); | |
}; | |
exports.rand = rand; | |
exports.randInt = randInt; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment