1 | const array_box_if_string = n => typeof n === 'string' ? [n] : n;
|
2 | const weighted_rand_select = (options, probability_property = 'probability') => {
|
3 | if (!Array.isArray(options)) {
|
4 | throw new TypeError('options must be a non-empty array of objects');
|
5 | }
|
6 | if (!(typeof options[0] === 'object')) {
|
7 | throw new TypeError('options must be a non-empty array of objects');
|
8 | }
|
9 | const frand = (cap) => Math.random() * cap, or_one = (item) => item === undefined ? 1 : item, prob_sum = options.reduce((acc, val) => acc + or_one(val[probability_property]), 0), rnd = frand(prob_sum);
|
10 | let cursor = 0, cursor_sum = 0;
|
11 | while ((cursor_sum += or_one(options[cursor++][probability_property])) <= rnd) { }
|
12 | return options[cursor - 1];
|
13 | };
|
14 | const seq = (n) => (new Array(n)).fill(true)
|
15 | .map((_, i) => i);
|
16 | const histograph = (ar) => ar.sort()
|
17 | .reduce((m, v) => (m.set(v, (m.has(v) ? m.get(v) + 1 : 1)), m), new Map());
|
18 | const weighted_sample_select = (n, options, probability_property) => seq(n)
|
19 | .map((_i) => weighted_rand_select(options, probability_property));
|
20 | const weighted_histo_key = (n, opts, prob_prop, extract) => histograph(weighted_sample_select(n, opts, prob_prop)
|
21 | .map((s) => s[extract]));
|
22 | export { seq, histograph, weighted_histo_key, weighted_rand_select, weighted_sample_select, array_box_if_string };
|