Last active
January 23, 2023 22:19
-
-
Save lpinca/5257771 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; |
@jitcoder
use 4294967296, crypto.randomBytes(4) can be 0xFFFFFFFF which is 4294967295
@jitcoder
use 4294967296, crypto.randomBytes(4) can be 0xFFFFFFFF which is 4294967295
👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
4294967296
should be 4294967295 no?
also thanks for putting this together, helped me not re-invent the wheel :D