-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
81 lines (64 loc) · 1.65 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
function * range(minimum, maximum) {
for (let number = minimum; number <= maximum; number++) {
yield number;
}
}
function randomInteger(minimum, maximum) {
return Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
}
function randomIntegerWithout(minimum, maximum, excludedValue) {
const number = randomInteger(minimum, maximum - 1);
return number >= excludedValue ? number + 1 : number;
}
function makeCallable(generator) {
const iterator = generator();
function random() {
return iterator.next().value;
}
random[Symbol.iterator] = function * () {
while (true) {
yield random();
}
};
return random;
}
export function consecutiveUniqueRandom(minimum, maximum) {
return makeCallable(function * () {
if (minimum === maximum) {
while (true) {
yield minimum;
}
}
let previousValue = randomInteger(minimum, maximum);
yield previousValue;
while (true) {
previousValue = randomIntegerWithout(minimum, maximum, previousValue);
yield previousValue;
}
});
}
export function exhaustiveUniqueRandom(minimum, maximum) {
return makeCallable(function * () {
if (minimum === maximum) {
while (true) {
yield minimum;
}
}
let unconsumedValues = [...range(minimum, maximum)];
while (true) {
while (unconsumedValues.length > 1) {
yield unconsumedValues.splice(
randomInteger(0, unconsumedValues.length - 1),
1,
)[0];
}
const [previousValue] = unconsumedValues;
yield previousValue;
unconsumedValues = [...range(minimum, maximum)];
yield unconsumedValues.splice(
randomIntegerWithout(0, unconsumedValues.length - 1, previousValue - minimum),
1,
)[0];
}
});
}