build(deps-dev): apply updates
[benchmarks-js.git] / random.mjs
1 import { randomInt } from 'node:crypto'
2
3 import { bench, group, run } from 'tatami-ng'
4
5 import {
6 secureRandom,
7 secureRandomWithRandomValues,
8 } from './benchmark-utils.mjs'
9
10 const maximum = 281474976710655
11
12 /**
13 * @param max
14 * @param min
15 * @returns
16 */
17 function getSecureRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
18 if (max < min || max < 0 || min < 0) {
19 throw new RangeError('Invalid interval')
20 }
21 max = Math.floor(max)
22 if (min !== 0) {
23 min = Math.ceil(min)
24 return Math.floor(secureRandom() * (max - min + 1)) + min
25 }
26 return Math.floor(secureRandom() * (max + 1))
27 }
28
29 /**
30 * @param max
31 * @param min
32 * @returns
33 */
34 function getSecureRandomIntegerWithRandomValues (
35 max = Number.MAX_SAFE_INTEGER,
36 min = 0
37 ) {
38 if (max < min || max < 0 || min < 0) {
39 throw new RangeError('Invalid interval')
40 }
41 max = Math.floor(max)
42 if (min !== 0) {
43 min = Math.ceil(min)
44 return Math.floor(secureRandomWithRandomValues() * (max - min + 1)) + min
45 }
46 return Math.floor(secureRandomWithRandomValues() * (max + 1))
47 }
48
49 /**
50 * @param max
51 * @param min
52 * @returns
53 */
54 function getRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
55 if (max < min || max < 0 || min < 0) {
56 throw new RangeError('Invalid interval')
57 }
58 max = Math.floor(max)
59 if (min !== 0) {
60 min = Math.ceil(min)
61 return Math.floor(Math.random() * (max - min + 1)) + min
62 }
63 return Math.floor(Math.random() * (max + 1))
64 }
65
66 group('Random Integer Generator', () => {
67 bench('Secure random integer generator', () => {
68 getSecureRandomInteger(maximum)
69 })
70 bench('Secure random with getRandomValues() integer generator', () => {
71 getSecureRandomIntegerWithRandomValues(maximum)
72 })
73 bench('Crypto random integer generator', () => {
74 randomInt(maximum)
75 })
76 bench('Math random integer generator', () => {
77 getRandomInteger(maximum)
78 })
79 })
80
81 await run({
82 units: true,
83 })