Skip to content

Commit

Permalink
Add check for if total number of items is less than itemsPerPage when…
Browse files Browse the repository at this point in the history
… page is out of bounds (#1462)
  • Loading branch information
laurakwhit authored Jun 29, 2023
1 parent 5626eab commit 92f7bbf
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
4 changes: 4 additions & 0 deletions src/lib/stores/pagination.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,10 @@ describe('getStartingIndexForPage', () => {
expect(getStartingIndexForPage(100, 20, oneHundredResolutions)).toBe(80);
});

it('should return 0 for the something out of bounds if the total number of items is less than itemsPerPage', () => {
expect(getStartingIndexForPage(3, 101, oneHundredResolutions)).toBe(0);
});

it('should return 0 if given a negative number for the page', () => {
expect(getStartingIndexForPage(-10, 20, oneHundredResolutions)).toBe(0);
});
Expand Down
6 changes: 4 additions & 2 deletions src/lib/stores/pagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,10 @@ export const getStartingIndexForPage = (
if (isNaN(page)) return 0;

if (page <= 1) return 0;
if (page > getTotalPages(itemsPerPage, items))
return items.length - itemsPerPage;
if (page > getTotalPages(itemsPerPage, items)) {
const index = items.length - itemsPerPage;
return index > 0 ? index : 0;
}

return Math.floor(itemsPerPage * (page - 1));
};
Expand Down

0 comments on commit 92f7bbf

Please sign in to comment.