0.2.0 • Published 6 years ago
weighted-array v0.2.0
🎲 Weighted Array
Select a random element from a weighted array.
💾 Installation
The package is on the NPM registry as weighted-array
. Simply install it with your NPM client of choice.
🔧 Usage
First, import the module:
const weightedArray = require('weighted-array')
The select()
function takes an array of objects. Every object must have at least the key: weight: number
. This is a weight relative to each other object in the array.
There is also the selectUnique*()
ES6 generator which will return randomly but without sequential repeats.
Both return one object from the array, with the whole object intact.
📝 Example
// Import the module
const { select } = require('weighted-array')
const array = [
{ weight: 1, name: 'Ben' },
{ weight: 2, name: 'Jerry' },
]
console.log(select(array)) // -> Will return Jerry twice as often as Ben