Extract one or more random elements from a weighted array.
const items = [
{ original: "Bronze", weight: 20 },
{ original: "Silver", weight: 10 },
{ original: "Gold", weight: 3 },
{ original: "Platinum", weight: 1 },
];
const picker = new RandomPicker(items);
const result = picker.pick();
⭐️ If you like this library, don't forget to give it a star! ⭐️
# If you use npm
npm install wrand
# If you use yarn
yarn add wrand
If you use Deno, you can just import what you need from deno.land/x
import {
RandomPicker,
pick,
pickMany,
flatten,
} from "https://deno.land/x/wrand/mod.ts";
Hint: The test.ts file contains all possible examples. Thi is the best source of usage documentation.
You can use the RandomPicker object to pick one or more random elements from a weighted array. The array can be any type, objects are fine.
The best usage here is if you need to pick many items at different moments and you don't want to recreate the object every time.
const items = [
{ original: "Bronze", weight: 20 },
{ original: "Silver", weight: 10 },
{ original: "Gold", weight: 3 },
{ original: "Platinum", weight: 1 },
];
const picker = new RandomPicker(items);
Once the item is created, you can call all exposed methods, in particular pick and pickMany.
const result = picker.pick();
const results = picker.pickMany(10);
If you only need to pick one item sporadically, you can hide the object creation and use the standalone methods instead.
The syntax is much more concise but keep in mind that the object is created underneath, you just don't have the reference and the code looks shorter.
const items = [
{ original: "Bronze", weight: 20 },
{ original: "Silver", weight: 10 },
{ original: "Gold", weight: 3 },
{ original: "Platinum", weight: 1 },
];
const result = pick(items);
This is a high-level roadmap. You can find more in the open issues.
- RandomPicker class
- Multiple picks with option for duplicates
- Handle duplicates
- Standalone methods
- pick
- pickMany
- flatten
- Extra features
- Add badges to the documentation
- Allow for custom random function
- Keep coverage high and not forget edge cases
Contributions of any kind are welcome! You can find more info on CONTRIBUTING.md.