Skip to content

Instantly share code, notes, and snippets.

@MrYakobo
Last active July 7, 2020 16:22
Show Gist options
  • Save MrYakobo/bb44f79c4f00485998b58fde7e01e912 to your computer and use it in GitHub Desktop.
Save MrYakobo/bb44f79c4f00485998b58fde7e01e912 to your computer and use it in GitHub Desktop.
Google-like pagination algorithm
#!/usr/bin/env python3
# heavily inspired by https://jasonwatmore.com/post/2016/01/31/angularjs-pagination-example-with-logic-like-google
import math
def paginate(curr, itemsPerPage, numItems, numPagesToShowAtOnce):
# ceil here to make sure we don't miss anything
half = math.ceil(numPagesToShowAtOnce / 2)
numPages = math.ceil(numItems / itemsPerPage)
if numPages <= numPagesToShowAtOnce:
# show all pages
lo = 1
hi = numPages
else:
if curr <= half:
# lower bound
lo = 1
hi = numPagesToShowAtOnce
elif curr + half >= numPages:
# higher bound
lo = numPages - numPagesToShowAtOnce
hi = numPages
else:
# middle
lo = curr - half
hi = curr + half
# ellipsis check lower bound
if lo > 1:
print(" 1 ", end="")
if lo > 2:
print("...", end="")
# output the range, highlighting curr with []
for i in range(lo, hi + 1):
if i == curr:
print("[{}]".format(i), end="")
else:
print(" {} ".format(i), end="")
# ellipsis check upper bound
if hi < numPages - 1:
print("...", end="")
if hi < numPages:
print(" {} ".format(numPages), end="")
for curr in range(1, 25 + 1):
paginate(curr=curr, itemsPerPage=10, numItems=250, numPagesToShowAtOnce=10)
print()
# note that curr is always centered unless it's close to the
# outputs the following:
"""
[1] 2 3 4 5 6 7 8 9 10 ... 25
1 [2] 3 4 5 6 7 8 9 10 ... 25
1 2 [3] 4 5 6 7 8 9 10 ... 25
1 2 3 [4] 5 6 7 8 9 10 ... 25
1 2 3 4 [5] 6 7 8 9 10 ... 25
1 2 3 4 5 [6] 7 8 9 10 11 ... 25
1 2 3 4 5 6 [7] 8 9 10 11 12 ... 25
1 ... 3 4 5 6 7 [8] 9 10 11 12 13 ... 25
1 ... 4 5 6 7 8 [9] 10 11 12 13 14 ... 25
1 ... 5 6 7 8 9 [10] 11 12 13 14 15 ... 25
1 ... 6 7 8 9 10 [11] 12 13 14 15 16 ... 25
1 ... 7 8 9 10 11 [12] 13 14 15 16 17 ... 25
1 ... 8 9 10 11 12 [13] 14 15 16 17 18 ... 25
1 ... 9 10 11 12 13 [14] 15 16 17 18 19 ... 25
1 ... 10 11 12 13 14 [15] 16 17 18 19 20 ... 25
1 ... 11 12 13 14 15 [16] 17 18 19 20 21 ... 25
1 ... 12 13 14 15 16 [17] 18 19 20 21 22 ... 25
1 ... 13 14 15 16 17 [18] 19 20 21 22 23 ... 25
1 ... 14 15 16 17 18 [19] 20 21 22 23 24 25
1 ... 15 16 17 18 19 [20] 21 22 23 24 25
1 ... 15 16 17 18 19 20 [21] 22 23 24 25
1 ... 15 16 17 18 19 20 21 [22] 23 24 25
1 ... 15 16 17 18 19 20 21 22 [23] 24 25
1 ... 15 16 17 18 19 20 21 22 23 [24] 25
1 ... 15 16 17 18 19 20 21 22 23 24 [25]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment