Improve random integer array generation
[benchmarks-js.git] / random.js
CommitLineData
aa697b2f 1const Benchmark = require('benchmark')
d6c40713 2const { LIST_FORMATTER, secureRandom } = require('./benchmark-utils')
aa697b2f
JB
3
4const suite = new Benchmark.Suite()
5
6const maximum = 1000
7
aa697b2f
JB
8/**
9 * @param max
10 * @param min
7fd91296 11 * @returns
aa697b2f
JB
12 */
13function getSecureRandomInteger (max, min = 0) {
14 max = Math.floor(max)
15 if (min) {
16 min = Math.ceil(min)
17 return Math.floor(secureRandom() * (max - min + 1)) + min
18 }
19 return Math.floor(secureRandom() * (max + 1))
20}
21
22/**
23 * @param max
24 * @param min
7fd91296 25 * @returns
aa697b2f
JB
26 */
27function getRandomInteger (max, min = 0) {
28 max = Math.floor(max)
29 if (min) {
30 min = Math.ceil(min)
31 return Math.floor(Math.random() * (max - min + 1)) + min
32 }
33 return Math.floor(Math.random() * (max + 1))
34}
35
36suite
37 .add('Secure random integer generator', function () {
38 getSecureRandomInteger(maximum)
39 })
40 .add('Random integer generator', function () {
41 getRandomInteger(maximum)
42 })
43 .on('cycle', function (event) {
44 console.log(event.target.toString())
45 })
46 .on('complete', function () {
47 console.log(
48 'Fastest is ' + LIST_FORMATTER.format(this.filter('fastest').map('name'))
49 )
7fd91296 50 // eslint-disable-next-line n/no-process-exit
aa697b2f
JB
51 process.exit()
52 })
53 .run()