Skip to content

Instantly share code, notes, and snippets.

@lpinca
Last active January 23, 2023 22:19
Show Gist options
  • Save lpinca/5257771 to your computer and use it in GitHub Desktop.
Save lpinca/5257771 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;
@exoticknight
Copy link

@jitcoder
use 4294967296, crypto.randomBytes(4) can be 0xFFFFFFFF which is 4294967295

@jitcoder
Copy link

@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