Move random generator inputs check at the right place
[benchmarks-js.git] / random.js
CommitLineData
f10b1da0
JB
1const Benchmark = require('benny')
2const { secureRandom } = require('./benchmark-utils')
aa697b2f 3
f10b1da0 4const maximum = Number.MAX_SAFE_INTEGER
aa697b2f 5
aa697b2f
JB
6/**
7 * @param max
8 * @param min
7fd91296 9 * @returns
aa697b2f 10 */
f10b1da0 11function getSecureRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
aa697b2f 12 max = Math.floor(max)
da504870 13 if (min != null && min !== 0) {
aa697b2f
JB
14 min = Math.ceil(min)
15 return Math.floor(secureRandom() * (max - min + 1)) + min
16 }
17 return Math.floor(secureRandom() * (max + 1))
18}
19
20/**
21 * @param max
22 * @param min
7fd91296 23 * @returns
aa697b2f 24 */
f10b1da0 25function getRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
aa697b2f 26 max = Math.floor(max)
da504870 27 if (min != null && min !== 0) {
aa697b2f
JB
28 min = Math.ceil(min)
29 return Math.floor(Math.random() * (max - min + 1)) + min
30 }
31 return Math.floor(Math.random() * (max + 1))
32}
33
f10b1da0
JB
34Benchmark.suite(
35 'Random Integer Generator',
e2bfb549 36 Benchmark.add('Secure random integer generator', () => {
aa697b2f 37 getSecureRandomInteger(maximum)
f10b1da0 38 }),
e2bfb549 39 Benchmark.add('Random integer generator', () => {
aa697b2f 40 getRandomInteger(maximum)
f10b1da0
JB
41 }),
42 Benchmark.cycle(),
43 Benchmark.complete(),
fb341cfe
JB
44 Benchmark.save({
45 file: 'random-integer-generator',
46 format: 'json',
47 details: true
48 }),
49 Benchmark.save({
50 file: 'random-integer-generator',
51 format: 'chart.html',
52 details: true
53 }),
54 Benchmark.save({
55 file: 'random-integer-generator',
56 format: 'table.html',
57 details: true
58 })
f10b1da0 59)