AniUI Academy

Paginate a list with full metadata

mediumArrays & Objects+250 XPPractice

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.

Arguments

itemsArray
The full list to paginate.
pagenumber
The requested 1-based page. Clamped into the valid range.
perPagenumber
The page size. Forced to 1 when not an integer of at least 1.

Returns

{ items, page, perPage, totalItems, totalPages, hasPrev, hasNext } — The slice for the current page plus all the metadata a pager UI needs. page and perPage are the values actually used after clamping.

Examples

paginate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2, 3);
// {
//   items: [4, 5, 6],
//   page: 2, perPage: 3,
//   totalItems: 10, totalPages: 4,
//   hasPrev: true, hasNext: true,
// }
paginate([1, 2, 3], 9, 2).page;
// 2 — a page past the end is clamped to the last real page

paginate([], 1, 5).totalPages;
// 0 — an empty list has no pages

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.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.