-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom.mjs
82 lines (75 loc) · 1.87 KB
/
random.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { randomInt } from 'node:crypto'
import { bench, group, run } from 'tatami-ng'
import {
secureRandom,
secureRandomWithRandomValues,
} from './benchmark-utils.mjs'
const maximum = 281474976710655
/**
* @param max
* @param min
* @returns
*/
function getRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
if (max < min || max < 0 || min < 0) {
throw new RangeError('Invalid interval')
}
max = Math.floor(max)
if (min !== 0) {
min = Math.ceil(min)
return Math.floor(Math.random() * (max - min + 1)) + min
}
return Math.floor(Math.random() * (max + 1))
}
/**
* @param max
* @param min
* @returns
*/
function getSecureRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
if (max < min || max < 0 || min < 0) {
throw new RangeError('Invalid interval')
}
max = Math.floor(max)
if (min !== 0) {
min = Math.ceil(min)
return Math.floor(secureRandom() * (max - min + 1)) + min
}
return Math.floor(secureRandom() * (max + 1))
}
/**
* @param max
* @param min
* @returns
*/
function getSecureRandomIntegerWithRandomValues (
max = Number.MAX_SAFE_INTEGER,
min = 0
) {
if (max < min || max < 0 || min < 0) {
throw new RangeError('Invalid interval')
}
max = Math.floor(max)
if (min !== 0) {
min = Math.ceil(min)
return Math.floor(secureRandomWithRandomValues() * (max - min + 1)) + min
}
return Math.floor(secureRandomWithRandomValues() * (max + 1))
}
group('Random Integer Generator', () => {
bench('Secure random integer generator', () => {
getSecureRandomInteger(maximum)
})
bench('Secure random with getRandomValues() integer generator', () => {
getSecureRandomIntegerWithRandomValues(maximum)
})
bench('Crypto random integer generator', () => {
randomInt(maximum)
})
bench('Math random integer generator', () => {
getRandomInteger(maximum)
})
})
await run({
units: true,
})