← 中文资源

简体中文版本

readonly 数组参数防止被重排

函数边界用 readonly T[] 接收数组:sort/reverse/push 在只读视图上不存在,同一份数组可以放心交给多个函数而无人能原地重排;latencies 与 metrics 都声明为 readonly,两个原地变异调用在编译期都被拒绝,计算前先展开拷贝。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

66.5
untouched: [ 72, 18, 133, 61 ]
[ { name: 'p99', value: 210 }, { name: 'p95', value: 133 } ]
order kept: [ 'p95', 'p50', 'p99' ]

实现说明

逻辑集中在函数 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 });