toSorted Sorts A Copy On Readonly Arrays

toSorted returns a new sorted array and accepts readonly inputs, so ranking views never reorder the source and nested tuples stay fully typed.

TypescriptData Integrity

Code

typescriptsnippet
17 lines
const deployments: ReadonlyArray<{ env: string; ts: number }> = [
  { env: 'prod', ts: 3 },
  { env: 'dev', ts: 1 },
  { env: 'prod', ts: 2 },
];

// toSorted 返回新数组:排序视图不改动源,readonly 输入也能接受
const sorted = deployments.toSorted((a, b) => a.ts - b.ts);
console.log(sorted.map((d) => d.env).join(','), '| source intact:', deployments.length);

// 只读元组数组同样成立:排序后取最便宜的一项
const prices: ReadonlyArray<readonly [string, number]> = [
  ['coffee', 320],
  ['tea', 280],
];
const cheapest = prices.toSorted((a, b) => a[1] - b[1])[0];
console.log(cheapest[0], cheapest[1], prices.length);

Output

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

dev,prod,prod | source intact: 3
tea 280 2

The program as a sequence

Demo state sits in top-level bindings: sorted, cheapest.

Watch out for

  • Copy, run: the standard library answers every call in the file.

Core lines

const sorted = deployments.toSorted((a, b) => a.ts - b.ts);
const cheapest = prices.toSorted((a, b) => a[1] - b[1])[0];

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `sorted`, `cheapest`.