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 generateRandomInteger(max: number): number { | |
if (max < 0 || !Number.isInteger(max)) { | |
throw new Error("Argument 'max' must be an integer greater than or equal to 0") | |
} | |
const bitLength = (max - 1).toString(2).length | |
const shift = bitLength % 8 | |
const bytes = new Uint8Array(Math.ceil(bitLength / 8)) | |
while (true) { | |
crypto.getRandomValues(bytes) | |
// This zeroes bits that can be ignored to increase the chance `result` < `max`. |
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 random(): number { | |
const buffer = new ArrayBuffer(8); | |
const bytes = crypto.getRandomValues(new Uint8Array(buffer)); | |
// sets the exponent value (11 bits) to 01111111111 (1023) | |
// since the bias is 1023 (2 * (11 - 1) - 1), 1023 - 1023 = 0 | |
// 2^0 * (1 + [52 bit number between 0-1]) = number between 1-2 | |
bytes[0] = 63; | |
bytes[1] = bytes[1] | 240; | |