Write a true modulo function in JavaScript
Intermediate · 3 min read
Lots of things in programs go round in a circle. After the last slide in a carousel comes the first. After Sunday comes Monday. Three hours before one o'clock is ten o'clock. To move around a circle like that, you need a modulo that always lands inside the range, even when you step backwards past the start.
JavaScript's % doesn't do that: -7 % 3 is -1. In this tutorial you will write a one-line helper, mod(n, m), that gives 2 instead, and use it to step through a list of bus stops and do clock arithmetic. You should know what % does, and that its answer takes the sign of the left-hand number.
What we want
Think of a clock with 3 positions: 0, 1 and 2. Counting forwards from 0 goes 0, 1, 2, 0, 1, 2. Counting backwards goes 0, 2, 1, 0, 2, 1. So:
mod(7, 3)should be 1, just like7 % 3.mod(-1, 3)should be 2: one step back from 0.mod(-7, 3)should be 2.
The rule: when m is positive, the answer is always between 0 and m - 1.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
24 A true modulo helper
fairWrite mod(n, m) that always takes the sign of m, so mod(-7, 3) is 2. Use it to wrap an array index and to do clock arithmetic.
Stuck? Three hints, smallest first
- 1. Take the remainder, add the modulus, take the remainder again.
- 2.
((n % m) + m) % m— the second%is what stops a positive input overshooting. - 3. For a 12-hour clock, three hours before one o’clock is
mod(1 - 3, 12).
Step 1: see the problem
console.log(-7 % 3); // -1
-1 is outside the range 0 to 2. But notice it is only one "lap" away from the right answer: -1 plus 3 is 2.
Step 2: add the modulus
So add m to the remainder:
const modTry = (n, m) => (n % m) + m;
console.log(modTry(-7, 3)); // 2: fixed
console.log(modTry(7, 3)); // 4, but it should be 1
The negative case works now. But a positive input already had a good remainder, and adding 3 pushes it out of range. This is the natural wrong turn.
Step 3: take the remainder again
After adding m, the value is never negative (for a positive m). One more % m brings anything too large back into range:
const mod = (n, m) => ((n % m) + m) % m;
console.log(mod(7, 3)); // 1
console.log(mod(-7, 3)); // 2
console.log(mod(-1, 5)); // 4
Each part has one job. The first % makes the number small. Adding m makes it non-negative. The second % trims a value that was already positive. Leave out either and one direction breaks.
Step 4: clock arithmetic
On a 12-hour clock, three hours before one o'clock is 1 - 3, which is -2. Wrap it:
console.log(mod(1 - 3, 12)); // 10
console.log(mod(26, 24)); // 2
Ten o'clock, as expected. The second line works on a 24-hour day: 26 hours after midnight is two in the morning.
Step 5: step around a list
Now the carousel case, with a list of bus stops. To move by places from position i, add the two and wrap the result by the length of the list:
const stops = ['Yaba', 'Surulere', 'Mushin', 'Oshodi', 'Ikeja'];
const step = (i, by) => stops[mod(i + by, stops.length)];
console.log(step(0, -1)); // Ikeja
console.log(step(4, 1)); // Yaba
One stop back from the first stop, Yaba, is the last stop, Ikeja. One stop forward from the last, at index 4, comes round to Yaba. You don't need any if (i < 0) i += n checks: mod handles both edges.
Step 6: a negative modulus
What if m itself is negative? The answer then takes the sign of m:
console.log(mod(7, -3)); // -2
You will rarely need this, but it shows the rule clearly: the result follows the sign of the modulus, while % follows the sign of the number being divided.
The full solution
The answer panel defines mod and step, then prints the positive and negative cases, the two clock questions and both edges of the bus route. The checks underneath confirm each one, including that % gave -1 where mod gives 2. Press Run to see the output.
const mod = (n, m) => ((n % m) + m) % m;
const stops = ['Yaba', 'Surulere', 'Mushin', 'Oshodi', 'Ikeja'];
const step = (i, by) => stops[mod(i + by, stops.length)];
console.log('mod(7, 3) :', mod(7, 3));
console.log('mod(-7, 3) :', mod(-7, 3), '<- where % gives', -7 % 3);
console.log('mod(-1, 5) :', mod(-1, 5));
console.log('clock : 3 hours before 1 is', mod(1 - 3, 12));
console.log('26 hours on :', mod(26, 24));
console.log('one stop back from Yaba:', step(0, -1));
console.log('mod(7, -3) :', mod(7, -3), '<- follows the modulus sign');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('mod agrees with % on positives', mod(7, 3), 1);
test('and gives a non-negative answer for a negative input', mod(-7, 3), 2);
test('where % gave -1', -7 % 3, -1);
test('wrapping an index backwards now lands on the last element', mod(-1, 5), 4);
test('three hours before one o clock is ten', mod(1 - 3, 12), 10);
test('twenty-six hours after midnight is two', mod(26, 24), 2);
test('stepping back from the first stop reaches the last', step(0, -1), 'Ikeja');
test('and forward past the end comes round again', step(4, 1), 'Yaba');
test('a negative modulus gives a negative result, matching the sign of m', mod(7, -3), -2);
The double % is doing exactly one job each. The first reduces the magnitude; adding m makes it non-negative; the second brings a value that was already positive back down, since otherwise mod(7, 3) would return 1 + 3. Leave either out and one of the two directions is wrong.
This is the helper for anything cyclic: carousel indexes, days of the week, clock faces, Caesar ciphers, hue angles. Once it exists, mod replaces every if (i < 0) i += n in the codebase, and the wrap-around edge stops needing its own test.
Common mistakes
- Using only
(n % m) + m. It fixes negatives but breaks positives:mod(7, 3)comes out as 4. - Wrapping with
%alone.(0 - 1) % 5is -1, andstops[-1]isundefined. - Wrapping by a fixed number. Use
stops.length, not 5, so the code keeps working when a stop is added.
Try it yourself
- Days of the week are numbered 0 (Sunday) to 6. Use
modto find the day 10 days before a Wednesday (3). - Write
prev(i)andnext(i)for a carousel of 4 slides, and test both edges. - Use
modto shift the letter'a'back by 3 places in the alphabet. You should get'x'.