Skip to content

Instantly share code, notes, and snippets.

@nusendra
Created March 12, 2020 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nusendra/e89206ee116c87bd97061784ac93aa6e to your computer and use it in GitHub Desktop.
Save nusendra/e89206ee116c87bd97061784ac93aa6e to your computer and use it in GitHub Desktop.
Pagination algorithm (only show some of the page from total page)
const pagingRange = (currentPage: number, { min = 1, totalPage = 20, length = 3 } = {}): Array<number> => {
if (length > totalPage) length = totalPage;
let start: number = currentPage - Math.floor(length / 2);
if (currentPage === totalPage) {
start = currentPage - Math.ceil(length / 2);
}
start = Math.max(start, min);
start = Math.min(start, min + totalPage - length);
return Array.from({length: length}, (el, i) => start + i);
}
console.log(pagingRange(20)) // [ 18, 19, 20 ]
console.log(pagingRange(4, { totalPage: 30, length: 3 })) // [ 3, 4, 5]
console.log(pagingRange(12, { totalPage: 12, length: 4})) // [ 9, 10, 11, 12 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment