Why does this pagination helper skip an item between pages?

Hey folks, I’m wiring up a tiny client-side pagination helper for a search results panel, and I’m trying to keep it simple without duplicating items or dropping one when the page size changes.

function getPage(items, page, pageSize) {
  const start = page * pageSize;
  const end = start + pageSize;
  return items.slice(start, end);
}

const items = ["a", "b", "c", "d", "e", "f", "g"];
console.log(getPage(items, 1, 3));
console.log(getPage(items, 2, 2));

Why does this kind of page math feel fine at first but then skip an item across views, and what index logic should I use if page numbers in my UI are meant to start at 1?

Yoshiii

@Yoshiii yup, the bug is just that your helper is using zero-based page math while your UI is one-based. If page 1 in the UI should start at index 0, the start index needs to be (page - 1) * pageSize.


js
function getPage(items, page, pageSize) {
  const start = (page - 1) * pageSize;
  return items.slice(start, start + pageSize);
}

Concrete example with your array: page 1, size 3 gives ["a", "b", "c"], but page 2, size 2 gives ["c", "d"] because changing the page size changes where that page number lands. So if pageSize changes, reset to page 1 or keep an absolute item offset instead of reusing the old page number.

WaffleFries