Apply dependencies update
[benchmarks-js.git] / random.js
1 const Benchmark = require('benchmark')
2 const { LIST_FORMATTER, secureRandom } = require('./benchmark-utils')
3
4 const suite = new Benchmark.Suite()
5
6 const maximum = 1000
7
8 /**
9 * @param max
10 * @param min
11 * @returns
12 */
13 function 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
25 * @returns
26 */
27 function 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
36 suite
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 )
50 // eslint-disable-next-line n/no-process-exit
51 process.exit()
52 })
53 .run()