random-sampler
This library provides APIs that useful for sampling a set of data, using normal or weighted possibility.
Installation
yarn add random-sampler
Explaination
Usage
Initialization
By default, simply new
an instance will provide all API that you need. In this case, Math.random
is used as default function to generate random numbers.
; const sampler = ;
You could also pass a random generator function when creating instance. Whenever called, it should produce uniform distribution with range [0, 1)
.
;; const generator = ; { return generator;}const sampler = getRandom;
Shuffle Array
By default, API will use Fish-Yates shuffle algorithm to shuffle array.
; const sampler = ;const array = 1 2 3;sampler;console;
If you provide a function to give weight for each element in array, shuffle will be based on their weights, meaning that possibility of each element to be selected first is different. In general, if there are elements a1
, a2
, ..., an
with weights w1
, w2
, ..., wn
, element ai
is selected as first element will have possibility wi / (w1 + w2 + ... + wn)
.
; const sampler = ;const array = 1 2 3; { return element + index;}sampler;console;
Notice: shuffle API will mutate given array. This is not a immutable API.
Sample Iterable
By default, it will use Reservoir algorithm to sample data out of array or any other iterable with size unknown:
; const sampler = ;const array = 1 2 3;const size = 2;const result = sampler;console;
If you provide a function to give weight for each element in array, sample will be based on their weights, meaning that possibility of each element to be selected is different (see how shuffle with weighted value works).
; const sampler = ;const array = 1 2 3;const size = 2; { return element + index;}const result = sampler;console;
When weights are provided, the element with larger weight will be more likely to be shown in front of sample result.
Notice: sample API will not mutate given array, but instead, it will produce a new array as result.
Asynchronous Sampling
When data cannot be provided synchronously, it's also possible to asynchronously add all elements and get the sample result whenever whished.
; const sampler = ;const size = 2;const receiver = sampler; window; // at some point:console;
.create(number)
function will return an object with two available APIs: add
and get
, where add
allows you to add elements and get
allows you to get the result based on current status.
If you provide a second parameter as a function providing weights to each element, weighted random sampling will be used. But still, the return of create(number, function)
will provide two available options, i.e. add
and get
as described above.
; const sampler = ;const size = 2; { return elementlength * index; }window; // at some point:console;