实现说明
各个操作都建立在顶层绑定之上:copy、rotated。
使用要点
- 每一步打印都带着自己的标签:
invalid index throws RangeError:。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 文件的状态由几个模块级绑定持有:copy、rotated。
核心语句
const rotated = moves.with(0, moves[2]!).with(2, moves[0]!);
const moves: string[] = ['e2e4', 'e7e5', 'g1f3'];
const copy = moves.with(1, 'e4e5');
代码示例
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);
}