UNPKG

905 BJavaScriptView Raw
1
2/**
3 * Isomorphic module for true random numbers / buffers / uuids.
4 *
5 * Attention: falls back to Math.random if the browser does not support crypto.
6 *
7 * @module random
8 */
9
10import * as math from './math.js'
11import * as binary from './binary.js'
12import { cryptoRandomBuffer } from './isomorphic.js'
13
14export const rand = Math.random
15
16export const uint32 = () => new Uint32Array(cryptoRandomBuffer(4))[0]
17
18export const uint53 = () => {
19 const arr = new Uint32Array(cryptoRandomBuffer(8))
20 return (arr[0] & binary.BITS21) * (binary.BITS32 + 1) + (arr[1] >>> 0)
21}
22
23/**
24 * @template T
25 * @param {Array<T>} arr
26 * @return {T}
27 */
28export const oneOf = arr => arr[math.floor(rand() * arr.length)]
29
30// @ts-ignore
31const uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11
32export const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c =>
33 (c ^ uint32() & 15 >> c / 4).toString(16)
34)