samplejs
can randomly sample elements from an array as well as keys of an object (where the value of the key is the weight).
npm install samplejs
import sample from 'samplejs';
// test has 2/5 chance of being picked
// all other elements have a 1/5 chance
var array = ['test', 'another', 'test', 'more', 'element'];
sample(array); //=> 'test' | 'another' | 'more' | 'element'
sample([]); //=> null
import sample from 'samplejs';
// key1 has 0.5/4.5 chance of being picked
// key2 has 3/4.5 chance of being picked
// key3 has 1/4.5 chance of being picked
var obj = {
key1: 0.5,
key2: 3,
key3: 1
};
sample(obj); //=> 'key1' | 'key2' | 'key3'
sample({}); //=> null