Modulo Wraps Negative Cyclic Indexes

The % operator keeps the dividend's sign, so backward steps yield negatives — the double-modulo idiom wraps any index back into range.

JavascriptData Integrity

Code

javascriptsnippet
17 lines
// % 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]);
}

Output

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

7 % 3 = 1
-7 % 3 = -1
wrap(-1): bridge
wrap(-2): chorus
wrap(9): verse
after 2 -> bridge
after 3 -> chorus
after -2 -> intro

A closer look

Modulo Wraps Negative Cyclic Indexes comes down to the function wrap.

The loop for (const delta of [2, 3, -2]) is the only repeated construct.

What to watch for

  • The environment needs no preparation beyond having the interpreter or compiler.

Putting it to use

Signature: const wrap = (index, length)

Output lines are prefixed (7 % 3 =, -7 % 3 =, wrap(-1):), so each line points back to the step behind it.

Core lines

const wrap = (index, length) => ((index % length) + length) % length;

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `wrap` at load time.