#1 · Off by one

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

Bug 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.

JavaScriptClick the line you think is wrong
// 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 it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
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

  1. Reproduce with a tiny list: five items, page 2, size 2. You expect ["c", "d"] and get ["c"]: one short.
  2. One short at the end of a range is the off-by-one signature, so look at how the range ends: end is 4, and the code slices to end - 1.
  3. Check the API: slice(start, end) leaves out end. The - 1 leaves 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’s range and Java’s subList are end-exclusive too.
  • SQL paging with LIMIT and OFFSET from a 1-based page number.
Your progress stays on this device.