Skip to content

Instantly share code, notes, and snippets.

@robbdimitrov
Last active March 24, 2023 05:50
Show Gist options
  • Save robbdimitrov/a9d13aabb2fa4a2ada7d24a6f33f19d9 to your computer and use it in GitHub Desktop.
Save robbdimitrov/a9d13aabb2fa4a2ada7d24a6f33f19d9 to your computer and use it in GitHub Desktop.
Pagination with dots
function getPages(maxPages, currentPage) {
let pages = [];
for (let i = 1; i <= maxPages; i++) {
if (i === 1 || i === maxPages ||
(currentPage < 4 && i <= 4) ||
(i >= currentPage - 1 && i <= currentPage + 1) ||
(maxPages - currentPage < 3 && maxPages - i <= 3)) {
pages.push(i);
} else if (pages[pages.length - 1] !== '...') {
pages.push('...');
}
}
return pages;
}
console.log(JSON.stringify(getPages(10, 1))); // [1,2,3,4,"...",10]
console.log(JSON.stringify(getPages(10, 2))); // [1,2,3,4,"...",10]
console.log(JSON.stringify(getPages(10, 3))); // [1,2,3,4,"...",10]
console.log(JSON.stringify(getPages(10, 4))); // [1,"...",3,4,5,"...",10]
console.log(JSON.stringify(getPages(10, 5))); // [1,"...",4,5,6,"...",10]
console.log(JSON.stringify(getPages(10, 6))); // [1,"...",5,6,7,"...",10]
console.log(JSON.stringify(getPages(10, 7))); // [1,"...",6,7,8,"...",10]
console.log(JSON.stringify(getPages(10, 8))); // [1,"...",7,8,9,10]
console.log(JSON.stringify(getPages(10, 9))); // [1,"...",7,8,9,10]
console.log(JSON.stringify(getPages(10, 10))); // [1,"...",7,8,9,10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment