weighted-map

Select a random element from a Map<element, weight>

Usage no npm install needed!

<script type="module">
  import weightedMap from 'https://cdn.skypack.dev/weighted-map';
</script>

README

🎲 Weighted Map

NPM version NPM downloads Build status Dependencies Coverage Status

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'

❤ Thanks