Commit | Line | Data |
---|---|---|
343cfe4f JB |
1 | const crypto = require('crypto') |
2 | ||
3 | /** | |
4 | * Generate a cryptographically secure random number in the [0,1[ range | |
5 | * | |
6 | * @returns | |
7 | */ | |
8 | function secureRandom () { | |
9 | return crypto.randomBytes(4).readUInt32LE() / 0x100000000 | |
10 | } | |
11 | ||
e9bfc28e JB |
12 | /** |
13 | * @param max | |
14 | * @param min | |
15 | */ | |
ed2968f2 | 16 | function generateRandomInteger (max, min = 0) { |
343cfe4f JB |
17 | if (max < 0) { |
18 | throw new RangeError('Invalid interval') | |
19 | } | |
20 | max = Math.floor(max) | |
ed2968f2 | 21 | if (min) { |
343cfe4f JB |
22 | if (max < min || min < 0) { |
23 | throw new RangeError('Invalid interval') | |
24 | } | |
25 | min = Math.ceil(min) | |
26 | return Math.floor(secureRandom() * (max - min + 1)) + min | |
ed2968f2 | 27 | } |
343cfe4f | 28 | return Math.floor(secureRandom() * (max + 1)) |
ed2968f2 JB |
29 | } |
30 | ||
a9c78d5d JB |
31 | /** |
32 | * @param ms | |
33 | */ | |
34 | async function sleep (ms) { | |
35 | return new Promise(resolve => setTimeout(resolve, ms)) | |
36 | } | |
37 | ||
ed2968f2 JB |
38 | const LIST_FORMATTER = new Intl.ListFormat('en-US', { |
39 | style: 'long', | |
40 | type: 'conjunction' | |
41 | }) | |
42 | ||
343cfe4f | 43 | module.exports = { generateRandomInteger, sleep, secureRandom, LIST_FORMATTER } |