with Copies Arrays And Swaps Elements

Array.prototype.with returns a copy with one index replaced, accepts negative indices, throws RangeError beyond length, and keeps the source untouched.

TypescriptData Integrity

Code

typescriptsnippet
17 lines
const moves: string[] = ['e2e4', 'e7e5', 'g1f3'];

// with(index, value):拷贝数组只换一个下标,源不动
const copy = moves.with(1, 'e4e5');
console.log(JSON.stringify(copy), '| source intact:', JSON.stringify(moves));

// 两次 with 串起来就是首尾交换
const rotated = moves.with(0, moves[2]!).with(2, moves[0]!);
console.log(JSON.stringify(rotated));

// 负下标从尾部计数;越界抛 RangeError
console.log(JSON.stringify([1, 2, 3].with(-1, 99)));
try {
  [1, 2, 3].with(7, 0);
} catch (e) {
  console.log('invalid index throws RangeError:', e instanceof RangeError);
}

Output

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

["e2e4","e4e5","g1f3"] | source intact: ["e2e4","e7e5","g1f3"]
["g1f3","e7e5","e2e4"]
[1,2,99]
invalid index throws RangeError: true

How the snippet proceeds

Top-level bindings copy, rotated hold the demo state — nothing sits inside a function scope.

Caveats

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Applying it

The demo output is labeled (invalid index throws RangeError:); each label names the call that printed it.

Statements that matter

const rotated = moves.with(0, moves[2]!).with(2, moves[0]!);
const moves: string[] = ['e2e4', 'e7e5', 'g1f3'];
const copy = moves.with(1, 'e4e5');

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `copy`, `rotated`.