Skip to content

Instantly share code, notes, and snippets.

@rfl890
Created July 9, 2023 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rfl890/496f23709c2661f29ac12d01a82e56f7 to your computer and use it in GitHub Desktop.
Save rfl890/496f23709c2661f29ac12d01a82e56f7 to your computer and use it in GitHub Desktop.
BigInt Ra NDom
function findClosestBits(n) {
return BigInt('0b' + n.toString(2).replaceAll('0', '1'))
}
// Returns a uniform random value in [0, max)
function rand(max) {
if (max <= 0) throw new Error("Argument max must be > 0");
if (max > 0xFFFFFFFFFFFFFFFFn) throw new Error("Argument max must be <= 0xFFFFFFFFFFFFFFFF");
const randomNumber = new BigUint64Array(1);
crypto.getRandomValues(randomNumber);
let ourNumber;
do {
const bytesToHoldMax = findClosestBits(max);
const randomNumberInOurRange = randomNumber[0] & bytesToHoldMax;
ourNumber = randomNumberInOurRange;
crypto.getRandomValues(randomNumber);
} while (ourNumber > max);
return ourNumber;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment