Created
October 31, 2022 16:41
-
-
Save richardiwnl/43ab976a8ff39b1afdacecbd1f5f7b03 to your computer and use it in GitHub Desktop.
Pagination algorithm for web applications
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
def make_pagination(current: int, last: int, delta: int=2) -> list: | |
pagination_range = [] | |
pagination_range_with_dots = [] | |
left = None | |
for i in range(1, last + 1): | |
if (i == 1 or i == last | |
or i >= current - delta | |
and i < current + delta + 1): | |
pagination_range.append(i) | |
for i in pagination_range: | |
if left is not None: | |
if i - left == 2: | |
pagination_range_with_dots.append(left + 1) | |
elif i - left != 1: | |
pagination_range_with_dots.append('...') | |
left = i | |
pagination_range_with_dots.append(i) | |
return pagination_range_with_dots | |
print(make_pagination(1, 10)) # [1, 2, 3, '...', 10] | |
print(make_pagination(6, 15)) # [1, '...', 4, 5, 6, 7, 8, '...', 15] | |
print(make_pagination(1, 10, delta=3)) # [1, 2, 3, 4, '...', 10] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment