Miss any of our Open RFC calls?Watch the recordings here! »

This package has been deprecated

Author message:

Deprecated in favour of weighted-map

weighted-array

0.2.0 • Public • Published

🎲 Weighted Array

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-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

❤ Thanks

Install

npm i weighted-array

DownloadsWeekly Downloads

1

Version

0.2.0

License

ISC

Unpacked Size

107 kB

Total Files

28

Last publish

Collaborators

  • avatar