-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·58 lines (44 loc) · 1.66 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
51
52
53
54
55
56
57
58
import crypto from 'crypto';
if(typeof window !== 'undefined') throw new Error("This module is not safe for client execution");
// crypto above 4 bytes is unreliable
const getRandomSample = () => crypto.randomBytes(4).readUInt32LE();
// ensure the value is between 0 and 2^32
const isInExtendedRange = (sample, range) =>
sample < (Math.floor(Math.pow(2, 32) / range) * range);
// unsafeCoerce should be removed, preferring safety to success
const unsafeCoerce = (sample, range) => sample % range;
const sample = (range, rangeCheck, coerce) => {
let sample;
let i = 0;
do {
sample = getRandomSample();
} while (100 > ++i && !rangeCheck(sample, range));
// note that if i is exceeded, the sample may be biased
return coerce(sample, range);
}
// get rand in range could easily invoke sample directly
const randIntBelow = val => sample(val, isInExtendedRange, unsafeCoerce);
export const getRandInRange = (min, max) => {
const lo = Math.ceil(min);
const hi = Math.floor(max);
return lo + randIntBelow(hi - lo + 1);
};
export const getString = validCharsString => {
const opts = validCharsString.split("");
const genStringOfLen = (curr, len) => {
if(len <= 0) return curr;
return genStringOfLen(curr + opts[getRandInRange(0, opts.length - 1)], len - 1);
};
return len => genStringOfLen("", len);
};
function* stringGenerator(validCharString, len) {
const opts = validCharString.split("");
const genStringOfLen = (curr, len) => {
if(len <= 0) return curr;
return genStringOfLen(curr + opts[getRandInRange(0, opts.length - 1)], len - 1);
};
while(true) {
yield genStringOfLen("", len);
}
}
// console.log(getString("abc")(5));