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