实现说明
底层就是函数 pickWeighted。
核心工作在嵌套循环里完成:外层 for (const entry of entries),内层 for (let i = 0; i < draws; i++)。这不是输入检查:RangeError 在耗尽路径上,循环跑完才会执行。
使用要点
- 守卫
entries.length === 0满足时靠提前的throw短路流程。
常见问题
循环什么时候会停?
当所有尝试耗尽时——throw 位于循环之后,只有最后一次尝试未能提前退出才会发生。
安装包是准备工作的一部分吗?
不需要。只用内建 API,安装这一步可以省掉。 文件在加载时定义 pickWeighted。
核心语句
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');
代码示例
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) + '%');
}