Coding Academy / Exercise

Calculate which records belong on a page

Build pagination bounds without losing the last record or requesting a page that does not exist.

You will learn to

  • Convert a page number to zero-based bounds
  • Clamp an out-of-range request
  • Handle an empty collection

Before you start

JavaScript arithmetic and objects

Write the contract

Implement pageWindow(total, size, requested). Inputs are integers: total is at least zero, size is positive, and requested can be any integer. Return {page, pages, start, end}. Page numbers start at one while record indexes start at zero. The end index is exclusive, matching Array.slice(start, end). For an empty collection return all four values as zero. Input validation for other types is outside this exercise.

Work through the last page

For 23 records and a page size of 10, Math.ceil(23 / 10) gives three pages. Page three starts at (3 - 1) * 10 = 20. Its end is min(20 + 10, 23) = 23. A slice from 20 to 23 contains exactly three records with indexes 20, 21 and 22. Using an inclusive end by mistake can duplicate or omit a record when moving between pages.

Clamp stale requests

A filter can reduce the number of records while the interface still requests page nine. Clamp the requested number between one and the total number of pages. For 23 records, a request for nine resolves to page three. A request for zero resolves to page one. Handle total zero before clamping, because an empty collection has no valid page one.

Connect the result to an interface

Use start and end to slice a local list; disable Previous on page one and Next on the last page. Do not load every remote record just to paginate a large database locally. Server pagination needs a separate request contract and stable ordering. This browser exercise calculates bounds only and makes no network requests. Test exact multiples, a partial last page and an empty collection.

Try it yourself

function pageWindow(total, size, requested) {
  // Return page, pages, start and exclusive end.
  return { page: 0, pages: 0, start: 0, end: 0 };
}
console.log(pageWindow(23, 10, 3));

Enable JavaScript for this interactive activity. You can read all lesson explanations above without it.

Continue exploring