JavaScriptFundamental (ES6), part 2
Paginate an array with page info in JavaScript
81 A paginator that reports the page it actually gave you
easyGiven a list of orders and a requested page, return the rows for that page plus everything a footer needs: how many pages there are, which page you are really on, whether there is a next or a previous page, and a "showing 1-10 of 23" label. Requests outside the range must be clamped rather than rejected, and an empty list must still describe itself sensibly.
Stuck? Three hints, smallest first
- 1. The page count is
Math.ceil(total / perPage)— but check what that gives for an empty list. - 2. Clamp the requested page into
1 .. pagesbefore you slice, and return the clamped number so the caller can render it. - 3.
slicepast the end of an array returns[]. It never throws, so you do not need to guard the upper bound.
const orders = Array.from({ length: 23 }, (_, i) => 'ORD-' + String(i + 1).padStart(3, '0'));
function paginate(items, { page = 1, perPage = 10 } = {}) {
const total = items.length;
const pages = Math.max(1, Math.ceil(total / perPage)); // an empty list is still page 1 of 1
const current = Math.min(Math.max(1, Math.trunc(page)), pages);
const from = (current - 1) * perPage;
const rows = items.slice(from, from + perPage); // slice clamps for us
return {
page: current,
pages,
total,
rows,
hasNext: current < pages,
hasPrev: current > 1,
label: 'Showing ' + (total === 0 ? 0 : from + 1) + '-' + Math.min(from + perPage, total) + ' of ' + total,
};
}
const first = paginate(orders);
const last = paginate(orders, { page: 3 });
const wayPastTheEnd = paginate(orders, { page: 9 });
const beforeTheStart = paginate(orders, { page: 0 });
const nothingAtAll = paginate([], { perPage: 10 });
const exactFit = paginate(Array.from({ length: 30 }, (_, i) => i + 1), { page: 3, perPage: 10 });
console.log('page 1 :', first.label, '| next?', first.hasNext);
console.log('page 3 :', last.label, '| next?', last.hasNext);
console.log('page 9 :', 'asked for 9, got', wayPastTheEnd.page);
console.log('empty :', nothingAtAll.label, '| pages', nothingAtAll.pages);
Output
7 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('23 rows at 10 a page is 3 pages, and page 1 has no previous', [first.page, first.pages, first.hasPrev, first.hasNext], [1, 3, false, true]);
test('the first page is the first ten rows, with a human label', [first.rows.length, first.rows[0], first.label], [10, 'ORD-001', 'Showing 1-10 of 23']);
test('the last page holds the remainder and offers no next', [last.rows, last.hasNext, last.label], [['ORD-021', 'ORD-022', 'ORD-023'], false, 'Showing 21-23 of 23']);
test('a page past the end is clamped, and it says which page it gave you', [wayPastTheEnd.page, wayPastTheEnd.rows.length], [3, 3]);
test('page 0 clamps up to 1 rather than slicing from -10', [beforeTheStart.page, beforeTheStart.rows[0]], [1, 'ORD-001']);
test('an empty list is one empty page, not zero pages', [nothingAtAll.pages, nothingAtAll.rows, nothingAtAll.label], [1, [], 'Showing 0-0 of 0']);
test('when perPage divides exactly there is no phantom extra page', [exactFit.pages, exactFit.hasNext, exactFit.rows.length], [3, false, 10]);
Two off-by-one bugs live in every hand-written paginator, and both are asserted here. Math.ceil(0 / 10) is 0, so an empty list claims to have zero pages and the footer renders "page 1 of 0"; the Math.max(1, ...) is what stops that. And 30 rows at 10 a page is 3 pages, not 4 — Math.ceil gets that right, while the Math.floor(total / perPage) + 1 version people reach for first gives 4 and a final empty page.
Returning the clamped page number matters more than it looks. A user who bookmarks ?page=9, or a delete that shrinks the list under them, arrives asking for a page that no longer exists. Clamping and reporting means the UI highlights page 3 and the URL can be corrected; rejecting means an error screen for something that is not an error.
slice doing the clamping for you is the small mercy: orders.slice(200, 210) is [], not a throw and not undefined, so the upper bound needs no guard at all.