1 import { randomInt } from 'node:crypto'
3 import Benchmark from 'benny'
7 secureRandomWithRandomValues
8 } from './benchmark-utils.mjs'
10 const maximum = 281474976710655
17 function getSecureRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
18 if (max < min || max < 0 || min < 0) {
19 throw new RangeError('Invalid interval')
24 return Math.floor(secureRandom() * (max - min + 1)) + min
26 return Math.floor(secureRandom() * (max + 1))
34 function getSecureRandomIntegerWithRandomValues (
35 max = Number.MAX_SAFE_INTEGER,
38 if (max < min || max < 0 || min < 0) {
39 throw new RangeError('Invalid interval')
44 return Math.floor(secureRandomWithRandomValues() * (max - min + 1)) + min
46 return Math.floor(secureRandomWithRandomValues() * (max + 1))
54 function getRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
55 if (max < min || max < 0 || min < 0) {
56 throw new RangeError('Invalid interval')
61 return Math.floor(Math.random() * (max - min + 1)) + min
63 return Math.floor(Math.random() * (max + 1))
67 'Random Integer Generator',
68 Benchmark.add('Secure random integer generator', () => {
69 getSecureRandomInteger(maximum)
72 'Secure random with getRandomValues() integer generator',
74 getSecureRandomIntegerWithRandomValues(maximum)
77 Benchmark.add('Crypto random integer generator', () => {
80 Benchmark.add('Math random integer generator', () => {
81 getRandomInteger(maximum)
86 file: 'random-integer-generator',
91 file: 'random-integer-generator',
96 file: 'random-integer-generator',
100 ).catch(console.error)