Created
March 12, 2020 17:53
-
-
Save nusendra/e89206ee116c87bd97061784ac93aa6e to your computer and use it in GitHub Desktop.
Pagination algorithm (only show some of the page from total page)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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