Last active
January 1, 2019 17:27
-
-
Save petamoriken/29a14ee186adb7a0b96d05d0bfd10e71 to your computer and use it in GitHub Desktop.
Get random bigint value in range.
This file contains hidden or 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
/** | |
* @param {number} byteLength A QuotaExceededError DOMException is thrown if the requested length is greater than 65536 bytes. | |
* @returns {bigint} | |
*/ | |
function getRandomBigIntByByteLength(byteLength) { | |
const buffer = new Uint8Array(byteLength); | |
crypto.getRandomValues(buffer); | |
return buffer.reduce((prev, current) => (prev << 8n) + BigInt(current), 0n); | |
} | |
/** | |
* Return random bigint (min <= value < max) | |
* @param {bigint} min | |
* @param {bigint} max | |
*/ | |
export function getRandomBigInt(min, max) { | |
if (min >= max) { throw RangeError("min value must be less than max value in getRandomBigInt arguments"); } | |
const bitLength = BigInt((max - min).toString(2).length); | |
const byteLength = Number((bitLength + 7n) / 8n); | |
let random; | |
do { | |
random = getRandomBigIntByByteLength(byteLength) + min; | |
} while (random >= max); | |
return random; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment