0.5.16
Sampling with samplers
Currently it's difficult to retrieve multiple random values from an array, if you want the values to be guaranteed unique. For example, when taking 2 random values from the array [1, 2, 3, 4, 5]
, calling utils.sample[1, 2, 3, 4, 5])
twice is not guaranteed to return unique values; it may return 4
twice in a row.
This version adds a new function, utils.sampler
, which is a factory function (a function that returns a function). Calling utils.sampler(n)
returns a function that will act like utils.sample
, but will return a random subset of the array on which it's called, returning either n
values or all of the values in array (if fewer than n
). See a few examples below:
const sample2 = utils.sampler(2);
const arr = [1, 2, 3, 4, 5];
const sampled = sample2(arr); // may return [4, 2]
const sample6 = utils.sampler(6);
const shuffled = sample6(arr); // this will only have 5 elements, and be a shuffled version of `arr`
const sample1 = utils.sampler(1);
const singleValue = sample1(arr); // when called with 1, this acts exactly the same as `utils.sample`
const sample0 = utils.sampler(0);
const result = sample0(arr); // for 0 or negative values, always returns `null`
Like utils.sample
, multiple-value sample functions returned from utils.sampler
will also accept as a second parameter an array of numbers representing weighted values.
const sample2 = utils.sampler(2);
const arr = [1, 2, 3, 4, 5];
const weightsA = [100, 10, 1, 1, 1]; // weights do not have to be normalized (sum to 1)
sample2(arr, weightsA); // will probably but not always be [1, 2]
const weightsB = [100, 100, 1, 1, 1];
sample2(arr, weightsB); // will probably be either [1, 2] or [2, 1] (with equal likelihood)