Readonly Array Parameters Prevent Reordering

Accept readonly T[] at function boundaries so sort, reverse, and push fail to compile instead of mutating a caller's array behind its back.

TypescriptData Integrity

Code

typescriptsnippet
36 lines
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 });

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Step-by-step behavior

The machinery is the functions median and topMetrics.

The return value is newly constructed — inputs are never handed back.

Caveats

  • No project changes are required before running it.

Using it

The top signature is function median(values: readonly number[])

Output lines are prefixed (untouched:, order kept:), which lays each step’s effect out plainly.

The central lines

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];

Interactive Tools for This Topic

FAQ

Does `median` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `median`, `topMetrics` at load time.