-
Notifications
You must be signed in to change notification settings - Fork 576
/
randomInt.ts
59 lines (48 loc) · 1.38 KB
/
randomInt.ts
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
export default function randomInt(max: number): number;
export default function randomInt(min: number, max: number): number;
export default function randomInt(
max: number,
cb: (err: Error | null, n?: number) => void,
): void;
export default function randomInt(
min: number,
max: number,
cb: (err: Error | null, n?: number) => void,
): void;
export default function randomInt(
max: number,
min?: ((err: Error | null, n?: number) => void) | number,
cb?: (err: Error | null, n?: number) => void,
): number | void {
if (typeof max === "number" && typeof min === "number") {
[max, min] = [min, max];
}
if (min === undefined) min = 0;
else if (typeof min === "function") {
cb = min;
min = 0;
}
if (
!Number.isSafeInteger(min) ||
typeof max === "number" && !Number.isSafeInteger(max)
) {
throw new Error("max or min is not a Safe Number");
}
if (max - min > Math.pow(2, 48)) {
throw new RangeError("max - min should be less than 2^48!");
}
if (min >= max) {
throw new Error("Min is bigger than Max!");
}
const randomBuffer = new Uint32Array(1);
crypto.getRandomValues(randomBuffer);
const randomNumber = randomBuffer[0] / (0xffffffff + 1);
min = Math.ceil(min);
max = Math.floor(max);
const result = Math.floor(randomNumber * (max - min + 1)) + min;
if (cb) {
cb(null, result);
return;
}
return result;
}