Skip to content

Instantly share code, notes, and snippets.

@vip3r011
Forked from lpinca/prng.js
Created January 23, 2023 22:19
Show Gist options
  • Save vip3r011/4f614e700c8e73c4e8c153d518e2a337 to your computer and use it in GitHub Desktop.
Save vip3r011/4f614e700c8e73c4e8c153d518e2a337 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