实现说明
逻辑集中在函数 median、topMetrics里。
为结果新分配了一个值;入参原样保留。
使用要点
- 每一步打印都带着自己的标签:
untouched:、order kept:。
常见问题
median 会修改传入的参数吗?
不会。代码构造并返回新值,入参保持原样,对共享或冻结的数据结构调用是安全的。
包管理器会看到什么?
一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 median、topMetrics。
签名一览:function median(values: readonly number[])
核心语句
const sorted = [...values].sort((a, b) => a - b);
.sort((a, b) => b.value - a.value)
.slice(0, n);
return sorted.length % 2 === 0
? (sorted[mid - 1] + sorted[mid]) / 2
: sorted[mid];
代码示例
type Metric = { name: string; value: number };
// readonly T[] promises not to mutate the input:
// sort/reverse/push are missing from the readonly view.
function median(values: readonly number[]): number {
const sorted = [...values].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 === 0
? (sorted[mid - 1] + sorted[mid]) / 2
: sorted[mid];
}
function topMetrics(metrics: readonly Metric[], n: number): Metric[] {
// spread first: the original array keeps its order
return [...metrics]
.sort((a, b) => b.value - a.value)
.slice(0, n);
}
// latencies is typed readonly, so callers can hand the same array to
// several functions without any of them being able to reorder it.
const latencies: readonly number[] = [72, 18, 133, 61];
console.log(median(latencies));
console.log('untouched:', latencies);
const metrics: readonly Metric[] = [
{ name: 'p95', value: 133 },
{ name: 'p50', value: 61 },
{ name: 'p99', value: 210 },
];
console.log(topMetrics(metrics, 2));
console.log('order kept:', metrics.map((m) => m.name));
// These fail compilation — the readonly view hides the mutating methods:
// latencies.sort();
// metrics.push({ name: 'avg', value: 96 });