weighted-map
v1.0.0
Published
Select a random element from a Map<element, weight>
Downloads
22
Maintainers
Readme
🎲 Weighted Map
Select a random element from a weighted array.
💾 Installation
The package is on the NPM registry as weighted-map
. Simply install it with your NPM client of choice.
🔧 Usage
First, import the module:
const weightedMap = require('weighted-map')
The select()
function takes a Map. Maps should be of type Map<T, number>
where key T
is your object, and value number
is the relative weight for that key.
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-map')
const map = new Map()
.set('ben', 1)
.set('jerry', 2)
console.log(select(map)) // -> Will return 'jerry' twice as often as 'ben'