Created
July 9, 2023 20:33
-
-
Save rfl890/496f23709c2661f29ac12d01a82e56f7 to your computer and use it in GitHub Desktop.
BigInt Ra NDom
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
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