weighted-picker
TypeScript icon, indicating that this package has built-in type declarations

2.1.0 • Public • Published

weighted-picker

Dependency Status devDependency Status Build Status: Linux Build Status: Windows npm version Downloads gzip size

A library to pick a random item from weighted array.

install

npm i weighted-picker

usage

// nodejs:
import WeightedPicker from "weighted-picker";
// import WeightedPicker from "weighted-picker/nodejs"; // ES syntax
 
// browser(module):
// import WeightedPicker from "weighted-picker";
// import WeightedPicker from "weighted-picker/browser"; // ES module
 
// browser(script tag):
// <script src="weighted-picker/weighted-picker.min.js"></script>
 
const items = [
    { name: "a", weight: 1 },
    { name: "b", weight: 2 },
    { name: "c", weight: 3 },
    { name: "d", weight: 4 },
];
const picker = new WeightedPicker(items.length, index => items[index].weight);
let index = picker.pickOne();
index = picker.pickOne();
index = picker.pickOne();

or

import WeightedPicker from "weighted-picker";
 
const items = ["a", "b", "c", "d"];
const weights = [1, 2, 3, 4];
const picker = new WeightedPicker(items.length, index => weights[index]);
let index = picker.pickOne();
index = picker.pickOne();
index = picker.pickOne();

change logs

// v2
import WeightedPicker from "weighted-picker/nodejs";
import WeightedPicker from "weighted-picker/browser";
 
// v1
import { WeightedPicker } from "weighted-picker";

Readme

Keywords

none

Package Sidebar

Install

npm i weighted-picker

Weekly Downloads

2

Version

2.1.0

License

MIT

Unpacked Size

9.75 kB

Total Files

8

Last publish

Collaborators

  • plantain_00