Newer
Older
export class Math {
constructor() {}
uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.replace(/[xy]/g,
(c) => {
let r = global.Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
})
.toUpperCase();
}
checkUuid(uuid) {
return uuid.search(
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i) !==
-1
}
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
let MAX_UINT32 = 0xFFFFFFFF;
let range = max - min;
if (!(range <= MAX_UINT32)) {
throw new Error("Range of " + range + " covering " + min + " to " + max +
" is > " + MAX_UINT32 + ".");
} else if (min === max) {
return min;
} else if (!(max > min)) {
throw new Error("max (" + max + ") must be >= min (" + min + ").");
}
// We need to cut off values greater than this to avoid bias in distribution
// over the range.
let maxUnbiased = MAX_UINT32 - ((MAX_UINT32 + 1) % (range + 1));
let rand;
do {
rand = crypto.getRandomValues(new Uint32Array(1))[0];
} while (rand > maxUnbiased);
let offset = rand % (range + 1);
return min + offset;
}
uniqueRandomArray(amount, from, to) {
let found = [];
while (found < amount) {
let r = this.random(from, to);
if (found.indexOf(r) === -1) {
found.push(r);
}
}
return found;
}
}
exports.default = Math;