
Product
A New Overview in our Dashboard
We redesigned Socket's first logged-in page to display rich and insightful visualizations about your repositories protected against supply chain threats.
bentools-picker
Advanced tools
A TypeScript library for weighted random item selection with a flexible and intuitive API.
npm install bentools-picker
import { Picker } from 'bentools-picker';
// Create a picker with default options
const picker = new Picker(['A', 'B', 'C']);
const item = picker.pick(); // Random item with equal weights
You can set weights in three different ways:
Best for both object and scalar values:
interface Item {
name: string;
}
const items = [
{ name: 'Common' },
{ name: 'Rare' },
{ name: 'Epic' },
{ name: 'Legendary' }
];
const picker = new Picker(items, {
weights: [
[items[0], 100], // Common: very high chance
[items[1], 50], // Rare: high chance
[items[2], 20], // Epic: medium chance
[items[3], 5] // Legendary: low chance
]
});
Only available for scalar values (strings, numbers):
const namePicker = new Picker(['Common', 'Rare', 'Epic', 'Legendary'], {
weights: {
'Common': 100, // Very high chance
'Rare': 50, // High chance
'Epic': 20, // Medium chance
'Legendary': 5 // Low chance
}
});
Useful for setting weights dynamically:
const chainedPicker = new Picker(items)
.setWeight(items[0], 100) // Common: very high chance
.setWeight(items[1], 50) // Rare: high chance
.setWeight(items[2], 20) // Epic: medium chance
.setWeight(items[3], 5); // Legendary: low chance
// Create a picker that removes items after picking
const consumablePicker = new Picker(items, { shift: true });
// Each pick removes the item from the pool
while (true) {
try {
const item = consumablePicker.pick();
console.log(item.name);
} catch (e) {
if (e.name === 'EmptyPickerError') {
console.log('No more items!');
break;
}
throw e;
}
}
All options are optional with sensible defaults:
interface PickerOptions<T> {
// Remove items after picking (default: false)
shift?: boolean;
// Throw error when picking from empty pool (default: true)
errorIfEmpty?: boolean;
// Default weight for items without specific weight (default: 1)
defaultWeight?: number;
// Optional weight definitions
weights?: Array<[T, number]> | Record<string | number, number>;
}
The picker is fully type-safe:
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
// TypeScript knows the picked item is of type User
const picker = new Picker(users);
const user = picker.pick(); // type: User
console.log(user.name); // TypeScript knows .name exists
Picker<T>
The main class for weighted random selection.
T
- The type of items to pick from. Can be either a scalar (number, string, etc.) or an object type.constructor(items: T[], options: PickerOptions<T>)
interface PickerOptions<T> {
shift: boolean; // Remove picked items from the pool
errorIfEmpty: boolean; // Throw error on empty list
defaultWeight: number; // Default weight for items
weights?: Weights<T>; // Optional weights definition (array of tuples or record object)
}
type Weights<T> = Array<[T, Weight]> | Record<string | number, Weight>;
pick(): T | never
Picks a random item based on weights. May throw EmptyPickerError
if the list is empty and errorIfEmpty
is true.
setWeight(item: T, weight: number): this
Sets the weight for a specific item. Returns the picker instance for method chaining.
// Set weights individually
picker.setWeight(items[0], 100);
// Or chain multiple calls
picker
.setWeight(items[0], 100)
.setWeight(items[1], 50)
.setWeight(items[2], 20);
EmptyPickerError
Thrown when attempting to pick from an empty list with errorIfEmpty: true
.
try {
picker.pick();
} catch (error) {
if (error instanceof EmptyPickerError) {
// Handle empty list
}
}
The probability of an item being picked is proportional to its weight relative to the sum of all weights. For example:
const items = [1, 2, 3]; // weights: 100, 50, 25
In this case:
WeakMap
for objects and Map
for scalar values internally.JSON.stringify
for object keys)setWeight
method: Best for dynamic weight updatesEmptyPickerError
when errorIfEmpty
is true.Contributions are welcome! Please feel free to submit a Pull Request.
MIT.
FAQs
A TypeScript library for weighted random item selection
The npm package bentools-picker receives a total of 4 weekly downloads. As such, bentools-picker popularity was classified as not popular.
We found that bentools-picker demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
We redesigned Socket's first logged-in page to display rich and insightful visualizations about your repositories protected against supply chain threats.
Product
Automatically fix and test dependency updates with socket fix—a new CLI tool that turns CVE alerts into safe, automated upgrades.
Security News
CISA denies CVE funding issues amid backlash over a new CVE foundation formed by board members, raising concerns about transparency and program governance.