Paginate a list with full metadata
Client-side pagination looks trivial until the user is on page 5, filters the list down to 8 items, and the page goes blank. Clamping and the surrounding metadata are the whole job.
Implement paginate(items, page, perPage). page is 1-based. Return an object with exactly these seven properties: items (the slice for the current page), page (the page actually used after clamping), perPage (the page size actually used), totalItems (the input length), totalPages, hasPrev and hasNext. perPage is forced to 1 if it is not an integer of at least 1. totalPages is totalItems divided by perPage, rounded up, so it is 0 for an empty list. page is clamped to at least 1, and to at most totalPages when there is at least one page. hasPrev is true when the resolved page is above 1; hasNext is true when it is below totalPages. For an empty list the result is page 1, no items, and both flags false.
What it has to do
- Return exactly the keys
items,page,perPage,totalItems,totalPages,hasPrevandhasNext. - Clamp
pageto at least 1 and at mosttotalPages. - Force
perPageto 1 when it is not an integer of at least 1. - Round
totalPagesup, giving 0 for an empty list. - Report
hasPrevandhasNextagainst the clamped page.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.