Pagination range
Implement paginationRange(page, total, siblings = 1). Return the buttons a pager shows: always page 1 and the last page, the current page with siblings pages on each side, and the string … (one character, U+2026) where pages are skipped. When a gap would hide exactly one page, show that page instead of the dots. total is at least 1.
Start from
function paginationRange(page, total, siblings = 1) {
// Return the page numbers to show, with … for the gaps.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
First collect the page numbers that must show (a Set removes duplicates), and sort them.
Hint 2
Then walk the sorted pages and look at the gap to the previous one: a gap of 2 hides one page, so add that page; a bigger gap gets the dots.
Solution
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function paginationRange(page, total, siblings = 1) {
const pages = new Set([1, total]);
for (let p = page - siblings; p <= page + siblings; p++)
if (p >= 1 && p <= total) pages.add(p);
const sorted = [...pages].sort((a, b) => a - b);
const out = [];
sorted.forEach((current, index) => {
const gap = index === 0 ? 0 : current - sorted[index - 1];
if (gap === 2) out.push(current - 1);
else if (gap > 2) out.push("…");
out.push(current);
});
return out;
}What an interviewer looks for
A typical live-coding task: plain UI logic with off-by-one traps. Interviewers want the logic separated from the markup so it can be tested like this.