-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
37 lines (35 loc) · 927 Bytes
/
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
/**
* Generate function for inserting selected index in sorted lookup.
* @param {array} array
* @returns {function}
*/
const insort = (array) => (x, low = 0, high = array.length) => {
while (low < high) {
let mid = low + high >>> 1;
if (x < array[mid] - mid) {
high = mid;
}
else {
low = mid + 1;
}
}
const pos = x + low;
array.splice(low, 0, pos);
return pos;
}
/**
* Generate function sampling unique values without mutating array.
* @param {array} array
* @returns {function}
*/
const uniqueSampler = (array, random = Math.random) => {
const pos = insort([]);
let count = array.length;
return () => {
if (count === 0) {
throw new Error('No samples left to pick');
}
return array[pos(~~(random() * count--))];
}
}
export default uniqueSampler;