Last active
May 2, 2019 18:34
-
-
Save Mds92/de453e9b6376382add2e742e7f0d7f34 to your computer and use it in GitHub Desktop.
Pagination Algorithm in Typescript
This file contains hidden or 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
static getPagination(currentPage: number, totalPages: number): string[] { | |
const delta = 2, | |
left = currentPage - delta, | |
right = currentPage + delta + 1, | |
range: number[] = [], | |
rangeString: string[] = []; | |
let tmp = 0; | |
for (let i = 1; i <= totalPages; i++) { | |
if (i == 1 || i == totalPages || i >= left && i < right) { | |
range.push(i); | |
} | |
} | |
for (const i of range) { | |
if (tmp) { | |
if (i - tmp === 2) { | |
rangeString.push((tmp + 1).toString()); | |
} else if (i - tmp !== 1) { | |
rangeString.push('...'); | |
} | |
} | |
rangeString.push(i.toString()); | |
tmp = i; | |
} | |
return rangeString; | |
} | |
/* | |
Outputs: | |
[1, 2, 3, "...", 10] | |
[1, "...", 8, 9, 10, 11, 12, "...", 20] | |
[1, "...", 8, 9, 10] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment