-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
50 lines (44 loc) · 1.17 KB
/
index.js
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
const { randomBytes } = require('crypto');
const { promisify } = require('util');
let bytes = 4;
function Random(low = 0, high = 0) {
if (low == 0 && high == 0) {
let buf = randomBytes(bytes);
let num = buf.readUInt32BE(0) / (Math.pow(2, 32) - 1);
return num;
}
else {
let buf = randomBytes(bytes);
let num = buf.readUInt32BE(0) / (Math.pow(2, 32) - 1);
return Math.floor(num * (high - low + 1) + low);
}
}
async function RandomAsync(low = 0, high = 0) {
if (low == 0 && high == 0) {
let buf = await promisify(randomBytes)(bytes);
let num = buf.readUInt32BE(0) / (Math.pow(2, 32) - 1);
return num;
}
else {
let buf = await promisify(randomBytes)(bytes);
let num = buf.readUInt32BE(0) / (Math.pow(2, 32) - 1);
return Math.floor(num * (high - low + 1) + low);
}
}
function setBytes(num) {
if (num < 1) {
throw new Error('Number of bytes must be greater than 0');
}
else {
bytes = num;
}
}
//test random.async
Random.async().then((num) => {
console.log(num);
});
module.exports = {
Random,
RandomAsync,
setBytes
};