Skip to content

Instantly share code, notes, and snippets.

@eAmin
Forked from lpinca/prng.js
Created May 6, 2020 09:15
Show Gist options
  • Save eAmin/42a67cf3cc98169ca9bd0a4e6f17197d to your computer and use it in GitHub Desktop.
Save eAmin/42a67cf3cc98169ca9bd0a4e6f17197d to your computer and use it in GitHub Desktop.
Pseudorandom number generator based on crypto.randomBytes
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