实现说明
活动部件是函数 rank、percentile。
失败是响亮的:RangeError 在守卫分支上直接中止当前操作,不做降级。
使用要点
- 守卫
sorted.length === 0成立时借助提前的throw直接离开。 - 演示输出是带标签的(
p50:、p95:、p99:),每个操作都会留下自己的一行标注。
常见问题
前置条件不满足时如何报错?
校验先行——RangeError 标记失败(位于 sorted.length === 0),不会先做一半再失败。
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 rank、percentile。
入口签名:const rank = (p / 100)
核心语句
const latencies = [12, 18, 24, 31, 45, 67, 89, 120, 240, 480].sort((a, b) => a - b);
return sorted[lower] + (sorted[upper] - sorted[lower]) * fraction;
if (sorted.length === 0) throw new RangeError('empty sample');
代码示例
// Percentile from a sorted sample: linear interpolation blends the two
// neighbours around the fractional rank, the way perf metrics do
function percentile(sorted, p) {
if (sorted.length === 0) throw new RangeError('empty sample');
const rank = (p / 100) * (sorted.length - 1);
const lower = Math.floor(rank);
const fraction = rank - lower;
const upper = Math.min(lower + 1, sorted.length - 1);
return sorted[lower] + (sorted[upper] - sorted[lower]) * fraction;
}
const latencies = [12, 18, 24, 31, 45, 67, 89, 120, 240, 480].sort((a, b) => a - b);
console.log('p50:', percentile(latencies, 50).toFixed(1));
console.log('p95:', percentile(latencies, 95).toFixed(1));
console.log('p99:', percentile(latencies, 99).toFixed(1));
console.log('p0 is min:', percentile(latencies, 0) === latencies[0]);
console.log('p100 is max:', percentile(latencies, 100) === latencies[latencies.length - 1]);
// nearest-rank for comparison: the ceil(p/100 * n) th element, no blending
const nearest = latencies[Math.ceil(0.5 * latencies.length) - 1];
console.log('nearest-rank p50:', nearest, 'interpolated:', percentile(latencies, 50).toFixed(1));