Weighted Random Pick With Cumulative Weights
Roll one random number against cumulative weights so each item wins with probability proportional to its weight, then verify the split over many draws.
Code
interface Weighted<T> {
item: T;
weight: number;
}
// One roll against cumulative weights: each item wins its share
function pickWeighted<T>(entries: readonly Weighted<T>[]): T {
if (entries.length === 0) throw new RangeError('empty entries');
const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
const roll = Math.random() * total;
let cumulative = 0;
for (const entry of entries) {
cumulative += entry.weight;
if (roll < cumulative) return entry.item;
}
throw new RangeError('unreachable while weights are non-negative');
}
const variants = [
{ item: 'control', weight: 50 },
{ item: 'variant-a', weight: 30 },
{ item: 'variant-b', weight: 20 },
] satisfies readonly Weighted<string>[];
// Empirical split over many draws approaches the configured weights
const counts = new Map<string, number>();
const draws = 10000;
for (let i = 0; i < draws; i++) {
const picked = pickWeighted(variants);
counts.set(picked, (counts.get(picked) ?? 0) + 1);
}
for (const [variant, count] of counts) {
console.log(variant, ((count / draws) * 100).toFixed(1) + '%');
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
control 49.7%
variant-b 19.8%
variant-a 30.5%How it works
Weighted Random Pick With Cumulative Weights keeps everything in the function pickWeighted.
The nesting pairs for (const entry of entries) with for (let i = 0; i < draws; i++) — the inner runs once per outer step. Not an input check: RangeError is thrown on the exhaustion path, after the loop finishes without a successful exit.
Caveats
- The guard
entries.length === 0short-circuits the flow with an earlythrowwhen its condition holds.
Core lines
const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
throw new RangeError('unreachable while weights are non-negative');
if (entries.length === 0) throw new RangeError('empty entries');
Interactive Tools for This Topic
Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.Password GeneratorGenerate random passwords from selectable character classes using crypto.getRandomValues with rejection sampling and class guarantees.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.UUID v4 GeneratorGenerate cryptographically random UUIDs version 4 using the Web Crypto API. Produce single or batch UUIDs with optional uppercase formatting and copy-to-clipboard support.
FAQ
- When does the loop stop?
- When every attempt is spent: the throw sits behind the loop, so it happens only after the last attempt fails to exit early.
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `pickWeighted` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.