Skip to content

Instantly share code, notes, and snippets.

@pilcrowOnPaper
pilcrowOnPaper / crypto-random-integer.ts
Last active January 6, 2024 23:21
Generates a random integer between 0 and a max number.
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`.
@pilcrowOnPaper
pilcrowOnPaper / crypto-random.ts
Last active January 3, 2024 18:55
Cryptographically strong Math.random(). Generate cryptographically strong random float between 0-1. Uses 52 bits instead of 32.
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;