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