Find the bug · #1 · Off by one Easy JavaScript
Every page is one item short
A shop lists its products a page at a time, and every page comes out one product short.
On this page
The report
The shop shows its products a page at a time. Customers report that every page has one product fewer than it should, and some products never appear on any page at all.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Returns the items for one page. Pages start at 1.
function paginate(items, page, size) {
const start = (page - 1) * size;
const end = start + size;
return items.slice(start, end - 1);
}Read it, then pick a line.
What does slice do with its second argument: include it, or stop before it?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
const items = ['a', 'b', 'c', 'd', 'e'];
console.log(JSON.stringify(paginate(items, 1, 2)));
console.log(JSON.stringify(paginate(items, 2, 2)));It prints
["a"] ["c"]
It should print
["a","b"] ["c","d"]
Show the answer: the bug, the fix, and how you’d find it
The bug (line 5)
Line 5 slices to end - 1. But slice already stops before its end index, so subtracting one drops the last item of every page. Those items never show up anywhere.
The fix
2function paginate(items, page, size) {3 const start = (page - 1) * size;4 const end = start + size;5 return items.slice(start, end - 1);5 return items.slice(start, end);6}How you’d find it
- Reproduce with a tiny list: five items, page 2, size 2. You expect
["c", "d"]and get["c"]: one short. - One short at the end of a range is the off-by-one signature, so look at how the range ends:
endis 4, and the code slices toend - 1. - Check the API:
slice(start, end)leaves outend. The- 1leaves out one more.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
const items = ['a', 'b', 'c', 'd', 'e'];
assert.deepEqual(paginate(items, 2, 2), ['c', 'd']);
assert.deepEqual(paginate(items, 3, 2), ['e']);
assert.deepEqual(paginate([], 1, 10), []);Where else this bites
substring, Python’srangeand Java’ssubListare end-exclusive too.- SQL paging with
LIMITandOFFSETfrom a 1-based page number.