easyLogic ErrorsJavaScript

The boundary miss

A developer asked an AI assistant to slice a results array into pages of 10 items for a paginated table. The suggested code compiles and looks reasonable, but every page is missing its last row, and users keep reporting gaps between pages.

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

Why does every page returned by getPage have only 9 items instead of 10?

pageSize only defaults to 10 when the argument is undefined, not when it's 0.
start is computed before pageNumber is validated as a positive integer.
Array.prototype.slice's end argument is already exclusive, so subtracting 1 excludes the page's true last item.
pageNumber should start counting from 0, not 1.

Sign in with GitHub to submit an answer and track your progress.