Sub topic 10
Chaining copying methods into pipelines
This chapter assumes you already know toSorted, toSpliced, and with from the earlier chapters. It also assumes you know that map and filter return new arrays. Each copying method returns a fresh array, so you can call the next method directly on that result. This lets you write a sequence of changes as one readable expression, and the original array stays untouched.
Building a pipeline
Each step in a chain receives the array that the previous step produced. The original is read once, at the start, and never written to.
const tasks = ["write tests", "fix bug", "deploy"];
const plan = tasks
.toSpliced(1, 0, "code review") // ["write tests", "code review", "fix bug", "deploy"]
.toSorted() // ["code review", "deploy", "fix bug", "write tests"]
.with(-1, "write more tests"); // ["code review", "deploy", "fix bug", "write more tests"]
console.log(plan);
console.log(tasks); // ["write tests", "fix bug", "deploy"] (unchanged)You can mix in map, filter, and slice too, because they also return new arrays:
const scores = [72, 95, 88, 61, 90];
const podium = scores
.filter((s) => s >= 70)
.toSorted((a, b) => b - a)
.toSpliced(3) // keep only the first three
.map((s, i) => `${i + 1}. ${s}`);
console.log(podium); // ["1. 95", "2. 90", "3. 88"]
console.log(scores); // [72, 95, 88, 61, 90]If you call toSpliced(start) with no deleteCount, it removes everything from start to the end.
Common errors
A mutating method at the head of the chain
sort returns the same array it sorted. A chain that starts with sort therefore looks safe, but it has already changed the original by the time the copying step runs.
const nums = [3, 1, 2];
const desc = nums.sort((a, b) => a - b).toReversed();
console.log(desc); // [3, 2, 1]
console.log(nums); // [1, 2, 3] (mutated!)A mutating method after a copying step is harmless, because it only changes a temporary copy that nothing else references. nums.toSorted().reverse() leaves nums alone. Mixing the two kinds still makes the code harder to review, so prefer one style per chain.
Indices that no longer exist
Every step sees the array produced by the step before it, not the original. If an earlier step shrinks the array, a later with can point past the end and throw.
const items = ["a", "b", "c"];
try {
items.toSpliced(1).with(2, "z"); // toSpliced(1) leaves ["a"]
} catch (err) {
console.log(err instanceof RangeError); // true
}Cost of each step
Every copying method allocates a full new array, so a chain of k steps over n elements does about k × n work and creates k temporary arrays.
| Situation | Recommended approach |
|---|---|
| Small or medium arrays, readability matters | Chain copying methods |
| Very large arrays in a hot loop | Copy once with `[...arr]`, then use mutating methods on the copy |
| Must keep the original intact | Make sure no mutating method runs on the original |
Exercise
Given const xs = [5, 2, 9, 1], what does xs.toSorted((a, b) => a - b).toSpliced(0, 1).with(-1, 0) return, and what is xs afterward?
Show answer
toSorted gives [1, 2, 5, 9]. toSpliced(0, 1) removes the first element, giving [2, 5, 9]. with(-1, 0) replaces the last element, giving [2, 5, 0]. xs is still [5, 2, 9, 1].
Exercise
Why does ["c", "a", "b"].toSpliced(2).with(2, "z") throw, and what error does it throw?
Show answer
toSpliced(2) removes everything from index 2 onward, leaving ["c", "a"] with length 2. Index 2 is out of range for that array, so with throws a RangeError.