1.0.2 โข Published 6 months ago
@jswork/ratio-selector v1.0.2
ratio-selector
A lightweight JavaScript utility for weighted random selection based on ratios.
Features
- ๐ฏ Weighted random selection based on probability ratios
- ๐ฒ Precise probability distribution
- ๐ช Type safe with TypeScript support
- ๐งช Well tested with comprehensive test cases
Installation
yarn add @jswork/ratio-selectorUsage
import ratioSelector from '@jswork/ratio-selector';
// Basic usage - items with probability ratios
const items = [
{ name: 'A', value: 0.5 }, // 50% chance
{ name: 'B', value: 0.3 }, // 30% chance
{ name: 'C', value: 0.2 } // 20% chance
];
const result = ratioSelector(items);
// Returns: 'A' or 'B' or 'C' based on their probabilities
// Example: Reward distribution
const rewards = [
{ name: 'Common', value: 0.7 },
{ name: 'Rare', value: 0.25 },
{ name: 'Epic', value: 0.05 }
];
const reward = ratioSelector(rewards);
// Returns a reward type based on rarityNotes
- The sum of all values must be approximately 1
- Each item must have a
name(string) andvalue(number) property - Values represent probability ratios (e.g., 0.3 = 30% chance)
License
Code released under the MIT license.