AniUI Academy
medium+250 XPPractice

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, hasPrev and hasNext.
  • Clamp page to at least 1 and at most totalPages.
  • Force perPage to 1 when it is not an integer of at least 1.
  • Round totalPages up, giving 0 for an empty list.
  • Report hasPrev and hasNext against the clamped page.

Your workspace

Try it yourself
Loading playground...

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.