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.
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 pagesWhat 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.
Stuck? The javascript course covers everything this challenge needs.
- 1.slices the requested page and reports metadata
- 2.clamps a page beyond the end
- 3.clamps a page below one
- 4.handles an empty list
- 5.forces an invalid page size to one
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.