easyLogic ErrorsJavaScript
The off-by-one pagination
An AI assistant wrote a pagination helper function to extract a specific page of items from a list. It was asked to return items for page 1, page 2, etc. (where pages are 1-indexed, and each page has a size of `limit`). However, the output is incorrect. Why?
paginate.js
function getPaginatedItems(items, page, limit) {
const startIndex = page * limit;
const endIndex = startIndex + limit;
return items.slice(startIndex, endIndex);
}What is the logic error in calculating the pagination indexes?
The startIndex is offset; for page 1, it starts at limit instead of 0.
Array.slice is destructive and will mutate the original items array.
The endIndex should be startIndex + limit - 1 because slice is inclusive of the end boundary.
The page variable must be converted to a string before arithmetic operations.