Simple, fast and lightweight function to pick a random element from a weighted array.
npm install pick-random-weightedThe package contains a pick function that just works out-of-the box.
import pick from 'pick-random-weighted';
const colors = [
['Red', 30],
['Green', 20],
['Blue', 40]
];
const color = pick(colors);It also contains a Picker class that can be instantiated to create a custom picker.
import { Picker } from 'pick-random-weighted';
const picker = new Picker();
const colors = [
['Red', 30],
['Green', 20],
['Blue', 40]
];
const color = Picker.pick(colors);Returns a random value from the values array.
Type: Array
List of values to pick from.
Each element should be provided in the format [value, weight].
By default, and to keep a small footprint, the library uses Math.random() to generate the random number to pick the value.
If you need you can define a custom function to generate random values, you can create a function that returns fixed values to use on your unit tests or implement a more specialized library like random-js.
By overwriting pick.random you can define your custom function.
Remember the returned value should be a number within the [0,1) range.
import { Picker } from 'pick-random-weighted';
const picker = new Picker(function () {
return 0.3;
});
const colors = [
['Red', 30],
['Green', 20],
['Blue', 40]
];
const color = Picker.pick(colors);
// Will always return 'Green' since our custom random generator function always returns the same value.Contributions are always welcome! Please run npm test beforehand to ensure everything is ok.
If you use this package please consider starring it :)