build(deps-dev): apply updates
[benchmarks-js.git] / benchmark-utils.mjs
CommitLineData
0c01f51c 1import { getRandomValues, randomBytes, randomInt } from 'node:crypto'
343cfe4f
JB
2
3/**
4 * Generate a cryptographically secure random number in the [0,1[ range
343cfe4f
JB
5 * @returns
6 */
be798e12 7export function secureRandom () {
b77517ba 8 return randomBytes(4).readUInt32LE() / 0x100000000
343cfe4f
JB
9}
10
99d76a65 11/**
06e5b856 12 * Generate a cryptographically secure random number in the [0,1[ range
483585cc 13 * @returns
99d76a65 14 */
be798e12 15export function secureRandomWithRandomValues () {
b77517ba 16 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
99d76a65
JB
17}
18
aa418e78
JB
19/**
20 *
21 * @param max
22 * @param min
aa418e78
JB
23 * @returns
24 */
be798e12 25export function generateRandomFloat (max = Number.MAX_VALUE, min = 0) {
768c0780
JB
26 if (max < min) {
27 throw new RangeError('Invalid interval')
28 }
ae56b43d 29 if (max - min === Number.POSITIVE_INFINITY) {
aa418e78
JB
30 throw new RangeError('Invalid interval')
31 }
f45b29bf 32 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min
aa418e78
JB
33}
34
ed40d2b0
JB
35/**
36 *
37 * @param size
38 * @param max
feb629fe 39 * @param numberGenerator
67bc7194 40 * @returns
ed40d2b0 41 */
be798e12 42export function generateRandomNumberArray (
feb629fe
JB
43 size,
44 max = Number.MAX_VALUE,
45 numberGenerator = generateRandomFloat
46) {
47 const array = []
ed40d2b0 48 for (let i = 0; i < size; i++) {
feb629fe 49 array.push(numberGenerator(max))
ed40d2b0 50 }
feb629fe
JB
51 return array
52}
53
5b907dbf
JB
54/**
55 *
56 * @param sizeMax
57 * @param numberMax
58 * @param numberGenerator
59 * @returns
60 */
be798e12 61export function generateRandomObject (
5b907dbf
JB
62 sizeMax = 500,
63 numberMax = Number.MAX_VALUE,
64 numberGenerator = generateRandomFloat
65) {
1ccd0724 66 const size = randomInt(sizeMax)
5b907dbf
JB
67 const object = {}
68 for (let i = 0; i < size; i++) {
69 object[i.toString()] = numberGenerator(numberMax)
70 }
8e1fbc06 71 return object
5b907dbf
JB
72}
73
a9c78d5d
JB
74/**
75 * @param ms
7fd91296 76 * @returns
a9c78d5d 77 */
be798e12 78export async function sleep (ms) {
5ae65d59 79 return await new Promise(resolve => setTimeout(resolve, ms))
a9c78d5d 80}