1 import crypto from 'crypto'
2 import Benchmark from 'benny'
5 secureRandomWithRandomValues
6 } from './benchmark-utils.mjs'
8 const maximum = 281474976710654
15 function getSecureRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
16 if (max < min || max < 0 || min < 0) {
17 throw new RangeError('Invalid interval')
20 if (min != null && min !== 0) {
22 return Math.floor(secureRandom() * (max - min + 1)) + min
24 return Math.floor(secureRandom() * (max + 1))
32 function getSecureRandomIntegerWithRandomValues (
33 max = Number.MAX_SAFE_INTEGER,
36 if (max < min || max < 0 || min < 0) {
37 throw new RangeError('Invalid interval')
40 if (min != null && min !== 0) {
42 return Math.floor(secureRandomWithRandomValues() * (max - min + 1)) + min
44 return Math.floor(secureRandomWithRandomValues() * (max + 1))
52 function getRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
53 if (max < min || max < 0 || min < 0) {
54 throw new RangeError('Invalid interval')
57 if (min != null && min !== 0) {
59 return Math.floor(Math.random() * (max - min + 1)) + min
61 return Math.floor(Math.random() * (max + 1))
65 'Random Integer Generator',
66 Benchmark.add('Secure random integer generator', () => {
67 getSecureRandomInteger(maximum)
70 'Secure random with getRandomValues() integer generator',
72 getSecureRandomIntegerWithRandomValues(maximum)
75 Benchmark.add('Crypto random integer generator', (max = maximum, min = 0) => {
77 if (min != null && min !== 0) {
79 return Math.floor(crypto.randomInt(min, max + 1))
81 return Math.floor(crypto.randomInt(max + 1))
83 Benchmark.add('Math random integer generator', () => {
84 getRandomInteger(maximum)
89 file: 'random-integer-generator',
94 file: 'random-integer-generator',
99 file: 'random-integer-generator',
100 format: 'table.html',