https://github.com/luludotdev/weighted-array
Select a random element from a weighted array.
https://github.com/luludotdev/weighted-array
Last synced: 8 months ago
JSON representation
Select a random element from a weighted array.
- Host: GitHub
- URL: https://github.com/luludotdev/weighted-array
- Owner: luludotdev
- License: isc
- Created: 2018-04-05T16:57:06.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2023-01-04T21:43:09.000Z (over 3 years ago)
- Last Synced: 2024-05-02T04:09:48.026Z (about 2 years ago)
- Language: TypeScript
- Size: 1.05 MB
- Stars: 0
- Watchers: 2
- Forks: 1
- Open Issues: 8
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# 🎲 Weighted Map
[](https://www.npmjs.com/package/weighted-map)
[](https://www.npmjs.com/package/weighted-map)
[](https://travis-ci.org/lolPants/weighted-array)
[](https://david-dm.org/lolpants/weighted-array)
[](https://coveralls.io/github/lolPants/weighted-array?branch=master)
##### 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:
```js
const weightedMap = require('weighted-map')
```
The `select()` function takes a Map. Maps should be of type `Map` 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
```js
// 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
* [weighted-random](https://www.npmjs.com/package/weighted-random)