1 import { randomBytes, getRandomValues, randomInt } from 'node:crypto'
4 * Generate a cryptographically secure random number in the [0,1[ range
7 export function secureRandom () {
8 return randomBytes(4).readUInt32LE() / 0x100000000
12 * Generate a cryptographically secure random number in the [0,1[ range
15 export function secureRandomWithRandomValues () {
16 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
25 export function generateRandomFloat (max = Number.MAX_VALUE, min = 0) {
27 throw new RangeError('Invalid interval')
29 if (max - min === Infinity) {
30 throw new RangeError('Invalid interval')
32 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min
39 * @param numberGenerator
42 export function generateRandomNumberArray (
44 max = Number.MAX_VALUE,
45 numberGenerator = generateRandomFloat
48 for (let i = 0; i < size; i++) {
49 array.push(numberGenerator(max))
58 * @param numberGenerator
61 export function generateRandomObject (
63 numberMax = Number.MAX_VALUE,
64 numberGenerator = generateRandomFloat
66 const size = randomInt(sizeMax)
68 for (let i = 0; i < size; i++) {
69 object[i.toString()] = numberGenerator(numberMax)
78 export async function sleep (ms) {
79 return await new Promise(resolve => setTimeout(resolve, ms))