实现说明
底层就是函数 wrap。
for (const delta of [2, 3, -2]) 是唯一的迭代点——其余代码顺序执行一遍。
使用要点
- 直接运行文件,输出会带上标签,比如
7 % 3 =、-7 % 3 =、wrap(-1):——输出的每一行都能指回产生它的那次调用。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 wrap。
入口签名:const wrap = (index, length)
核心语句
const wrap = (index, length) => ((index % length) + length) % length;
代码示例
// % takes the sign of the dividend, not the divisor
console.log('7 % 3 =', 7 % 3);
console.log('-7 % 3 =', -7 % 3);
// Double modulo maps any integer — negative or past the end — into range
const wrap = (index, length) => ((index % length) + length) % length;
const playlist = ['intro', 'verse', 'chorus', 'bridge'];
console.log('wrap(-1):', playlist[wrap(-1, playlist.length)]);
console.log('wrap(-2):', playlist[wrap(-2, playlist.length)]);
console.log('wrap(9):', playlist[wrap(9, playlist.length)]);
// Stepping by any delta keeps the cursor inside the playlist
let cursor = 1;
for (const delta of [2, 3, -2]) {
cursor = wrap(cursor + delta, playlist.length);
console.log('after', delta, '->', playlist[cursor]);
}