random-picker
Version:
Randomly pick an item from a set (using the specified probabilities).
116 lines (78 loc) • 3.28 kB
Markdown
[](http://badge.fury.io/js/random-picker)
[](https://travis-ci.org/skratchdot/random-picker)
[](https://codeclimate.com/github/skratchdot/random-picker)
[](https://coveralls.io/github/skratchdot/random-picker?branch=master)
[](https://david-dm.org/skratchdot/random-picker)
[](https://david-dm.org/skratchdot/random-picker#info=devDependencies)
[](https://npmjs.org/package/random-picker)
Randomly pick an item from a set (using the specified probabilities).
## Getting Started
Install the module with: `npm install random-picker`
```javascript
var Picker = require('random-picker').Picker;
var picker = new Picker(); // or pass in a seed: var picker = new Picker(seed)
picker.option('male');
picker.option('female');
picker.pick(); // 50% chance of being 'male' or 'female'
picker.option('male', 22);
picker.option('female', 78);
picker.pick(); // now there's a 22% chance of being 'male', and a 78% change of being 'female'
picker.removeAll();
picker.option('good', 3.42)
picker.option('bad', 3.42)
picker.pick(); // now there's a 50% chance of being 'good' or 'bad'
```
- [Live example on Tonic](https://tonicdev.com/npm/random-picker)
Randomly pick an item from the options that were added. The probability of an
item being chosen is determined by the score that was given to the option.
Add an item to the list of available options that can be picked. A default
score of 1 is used if the score is not passed in.
Remove all the options that have been passed in.
Remove the given option if it exists.
Return how many options have been passed in.
What is the total score of the existing options?
What is the average score of the existing options?
Initialize a picker with a given seed:
```javascript
var picker = require('random-picker').Picker('Seed my random generator');
```
A random score of 1 is used by default:
```javascript
// if male/female are the only options, then the following:
picker.option('male');
picker.option('female');
// is the same as:
picker.option('male', 1);
picker.option('female', 1);
// or for that matter:
picker.option('male', 100);
picker.option('female', 100);
```
You can pass in functions as well. The following code will return
a random number 80% of the time, and 0.5 20% of the time:
```javascript
picker.option(function () {
return Math.random();
}, 80);
picker.option(function () {
return 0.5;
}, 20);
console.log(picker.pick()());
```
- initial release
Copyright (c) 2014 skratchdot
Licensed under the MIT license.