Learn about our RFC process, Open RFC meetings & more.Join in the discussion! »

weighted-map

1.0.0 • Public • Published

🎲 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

Install

npm i weighted-map

DownloadsWeekly Downloads

9

Version

1.0.0

License

ISC

Unpacked Size

9.01 kB

Total Files

16

Last publish

Collaborators

  • avatar