Skip to content

Instantly share code, notes, and snippets.

@guilouro
Last active October 12, 2018 15:03
Show Gist options
  • Save guilouro/05714065a8c13ccc1c5c779e51911e8a to your computer and use it in GitHub Desktop.
Save guilouro/05714065a8c13ccc1c5c779e51911e8a to your computer and use it in GitHub Desktop.
A simple pagination that return an array when passed current and total item.
def pagination(current, last):
delta = 2
left = current - delta
right = current + delta + 1
myrange = []
rangeWithDots = []
l = 0
for i in range(1, last+1):
if (i == 1 or i == last or i >= left and i < right):
myrange.append(i)
for i in myrange:
if l:
if (i - l) == 2:
rangeWithDots.append(l + 1)
elif (i - l) != 1:
rangeWithDots.append('...')
rangeWithDots.append(i)
l = i
return rangeWithDots
# HOW TO USE
for i in range(1, 21):
print('When current is {} with {} items: {}'.format(i, 20, pagination(i, 20)))
"""
Output:
When current is 1 with 20 items: [1, 2, 3, '...', 20]
When current is 2 with 20 items: [1, 2, 3, 4, '...', 20]
When current is 3 with 20 items: [1, 2, 3, 4, 5, '...', 20]
When current is 4 with 20 items: [1, 2, 3, 4, 5, 6, '...', 20]
When current is 5 with 20 items: [1, 2, 3, 4, 5, 6, 7, '...', 20]
When current is 6 with 20 items: [1, '...', 4, 5, 6, 7, 8, '...', 20]
When current is 7 with 20 items: [1, '...', 5, 6, 7, 8, 9, '...', 20]
When current is 8 with 20 items: [1, '...', 6, 7, 8, 9, 10, '...', 20]
When current is 9 with 20 items: [1, '...', 7, 8, 9, 10, 11, '...', 20]
When current is 10 with 20 items: [1, '...', 8, 9, 10, 11, 12, '...', 20]
When current is 11 with 20 items: [1, '...', 9, 10, 11, 12, 13, '...', 20]
When current is 12 with 20 items: [1, '...', 10, 11, 12, 13, 14, '...', 20]
When current is 13 with 20 items: [1, '...', 11, 12, 13, 14, 15, '...', 20]
When current is 14 with 20 items: [1, '...', 12, 13, 14, 15, 16, '...', 20]
When current is 15 with 20 items: [1, '...', 13, 14, 15, 16, 17, '...', 20]
When current is 16 with 20 items: [1, '...', 14, 15, 16, 17, 18, 19, 20]
When current is 17 with 20 items: [1, '...', 15, 16, 17, 18, 19, 20]
When current is 18 with 20 items: [1, '...', 16, 17, 18, 19, 20]
When current is 19 with 20 items: [1, '...', 17, 18, 19, 20]
When current is 20 with 20 items: [1, '...', 18, 19, 20]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment