Terminology (6)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Modulus Also n
- The size of the cycle: the number of slots in a ring buffer, buckets in a hash table or minutes in a day.
- Remainder Also %
- What % returns in TypeScript, Go, Rust and C++: dividend minus the truncated quotient times the divisor. It has the sign of the dividend, so it can be negative.
- Euclidean remainder Also p mod n
- The remainder from 0 to n − 1. It is the valid index for a slot or bucket. Rust calls it rem_euclid.
- Floor division
- The quotient rounded down, toward negative infinity. It pairs with the Euclidean remainder so that p = quotient × n + remainder.
- Ring buffer
- A fixed array whose writer wraps back to slot 0 after the last slot, overwriting the oldest entry.
- Wraparound
- Continuing past the last value of a cycle back to the first, as a region of slots or a time window can.
Why this matters
Ring buffers, hash tables, carousels and clock times all map an unbounded number onto n
slots. The index has to land from 0 to n − 1. When the number can be negative, because a
cursor moves backwards or a hash code is signed, the familiar % operator can return a
negative index. TypeScript then reads undefined, Go and Rust panic, and in
C++ the read is undefined behavior.
This lesson assumes division with a remainder and the signed integers from the previous lessons.
Positions on a repeating cycle
Modular arithmetic treats positions separated by a whole number of cycles as equivalent. With a positive capacity n, a slot is represented by an integer from 0 through n − 1. Several logical positions can therefore share one physical slot.
The slot answers where to store a line. A lap or generation distinguishes which turn supplied that line, and an occupancy check says whether the slot is currently live. These are separate pieces of the ring-buffer model; the worked example starts by inspecting the native remainder and division operators.
01Read % as a remainder
Read % as a remainder
A device log viewer keeps its last lines in a ring buffer. Scrolling back past the anchor gives a negative position, and position % capacity returned a negative index because % keeps the sign of the position.
The viewer is 17 lines before its anchor in an 8-slot buffer. Predict the three lines this program prints.
const position = -17; // 17 lines before the anchor
const capacity = 8;
console.log(position % capacity); // remainder
console.log(position / capacity); // quotient
console.log(((position % capacity) + capacity) % capacity); // slot
02Normalize the slot
Normalize the slot
The cursor sits in slot 2 and moves back 19 lines, to 2 − 19 = −17. A common repair adds the capacity once: (−17 + 8) % 8 = −9 % 8 = −1, still negative. One addition is guaranteed to work when the value is at least −n; it is not a general repair for an arbitrary signed position.
((p % n) + n) % n works for every p: the first % brings the value above −n, the addition
makes it positive, and the second % brings it below n. Rust’s rem_euclid does the same in one call. Within the lab’s capacity bounds, when
n is a power of two, p & (n − 1) also gives the Euclidean remainder in two’s complement: −1,234,567
& 15 is 9.
03Pair the lap with the slot
Pair the lap with the slot
The lap distinguishes positions that share a storage slot after a full turn, so the viewer does not confuse an old logical line with the line that replaced it. Position, lap and slot must satisfy p = lap × n + slot. The Euclidean slot pairs with the floor quotient, which rounds toward negative infinity. Truncating division rounds toward zero, so mixing it with a normalized slot breaks the identity: −2 × 8 + 7 = −9, not −17.
| p | truncated / and % | lap and slot |
|---|---|---|
| 17 | 2, 1 | 2, 1 |
| −1 | 0, −1 | −1, 7 |
| −16 | −2, 0 | −2, 0 |
| −17 | −2, −1 | −3, 7 |
04Regions that wrap
Regions that wrap
The buffer’s live lines start at the oldest one, the tail, and continue for len slots. With tail 6 and 5 live lines in 8 slots, they occupy 6, 7, 0, 1, 2. The end, (6 + 5) mod 8 = 3, is smaller than the start, so a check written as tail ≤ q < end finds nothing live.
Measuring the distance forward from the tail, (q − tail) mod n, turns the ring into a straight line that starts at the tail. Slot q is live when that distance is below len. Slot 4 is 6 steps from the tail, so it is stale. This test describes slot occupancy. To retrieve a particular historical line, also check its lap or generation; knowing its slot alone does not show that the line survived an overwrite.
05Full or empty
Full or empty
06Build the log viewer
Build the log viewer
Scrolling back first needs a valid array slot even many turns before the anchor. That slot alone forgets which turn the line came from, so pair it with a lap that reconstructs the signed position. The viewer also needs an occupancy check for the live region: its oldest slot and length must work when the region crosses zero, fills the buffer or becomes empty.
A device log viewer
Find the slot, count the laps, then tell live lines from stale ones.
In the frontend A wrapping carousel in Next.js and Svelte Optional
A carousel’s Previous button on the first slide should show the last one. Index − 1 is
−1 there, and (−1) % length is −1, which reads undefined from the array. The
Euclidean remainder wraps it to length − 1. An empty slide list has no valid index, so it
renders a placeholder; a remainder by 0 is NaN. If the slide list shrinks, normalize the displayed
index against its current length too.
"use client";
import { useState } from "react";
// Euclidean remainder: Previous on the first slide wraps to the last one.
const wrap = (index: number, count: number) => ((index % count) + count) % count;
export function Carousel({ slides }: { slides: string[] }) {
const [index, setIndex] = useState(0);
if (slides.length === 0) return <p>No slides</p>;
const current = wrap(index, slides.length);
return (
<figure>
<img src={slides[current]} alt="" />
<button onClick={() => setIndex((i) => wrap(i - 1, slides.length))}>
Previous
</button>
<button onClick={() => setIndex((i) => wrap(i + 1, slides.length))}>Next</button>
</figure>
);
}
See React useState and Svelte $state.
Check this idea later
Sources
- ECMAScript: Number::remainder
- Go specification: arithmetic operators
- Rust: i64::rem_euclid
- C++: multiplicative operators
Outputs above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The log viewer is a worked model.
Sign in to keep your read marks on every device. Sign in
Was this helpful?