Last active
July 3, 2017 13:27
-
-
Save vitaliiznak/60e4262f6b248f0b6ffd11cfe03201cc to your computer and use it in GitHub Desktop.
Pagination generator implemented in python
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
| import unittest | |
| #try it here https://repl.it/JLH2/2 | |
| """ | |
| >>> make_paginator(4,5,1,0) | |
| "1 ... 4 5" | |
| >>> make_paginator(4,10,2,2) | |
| "1 2 3 4 5 6 ... 9 10" | |
| >>> make_paginator(4,10,2,2) | |
| "1 2 3 4 5 6 ... 9 10" | |
| """ | |
| def make_paginator(current_page, total_pages, boundaries, arround): | |
| assert current_page >= 0, 'current_page is less than zero' | |
| assert total_pages >= 0, 'total_pages is less than zero' | |
| assert boundaries >= 0, ' boundaries is less than zero' | |
| assert arround >= 0, 'arround is less than zero' | |
| assert current_page <= total_pages, 'current_page is bigger than total_pages' | |
| start_initial_chunk = 1 | |
| end_initial_chunk = min( boundaries, total_pages) + 1 | |
| start_middle_chunk = max( end_initial_chunk, current_page - arround, 1 ) | |
| end_middle_chunk = min(current_page + arround, total_pages ) + 1 | |
| start_final_chunk =max( end_middle_chunk , total_pages - boundaries + 1, boundaries + 1) | |
| end_final_chunk = total_pages + 1 | |
| #initial chunk | |
| initial_chunk_numbers = list( range(start_initial_chunk, end_initial_chunk) ) | |
| #middle chunk | |
| middle_chunk_numbers = list( range(start_middle_chunk, end_middle_chunk) ) | |
| #end chunk | |
| final_chunk_numbers = list( range(start_final_chunk, end_final_chunk) ) | |
| prev_linker = ' ... ' if end_initial_chunk < start_middle_chunk and len(middle_chunk_numbers) > 0 else ' ' | |
| next_linker = ' ... ' if end_middle_chunk < start_final_chunk else '' if boundaries + 1 <=end_middle_chunk else ' ' | |
| return ( | |
| ' '.join( map(str, initial_chunk_numbers)) + prev_linker + | |
| ' '.join(map(str, middle_chunk_numbers)) + next_linker + | |
| ' '.join(map(str, final_chunk_numbers)) | |
| ).strip() | |
| class TestmakePaginator(unittest.TestCase): | |
| def test(self): | |
| self.assertEqual( 'foo', 'foo') | |
| self.assertEqual( make_paginator(2,2,0,0) , '... 2') | |
| self.assertEqual( make_paginator(2,4,0,0) , '... 2 ...') | |
| self.assertEqual( make_paginator(4,8,0,1) , '... 3 4 5 ...') | |
| self.assertEqual( make_paginator(4,8,1,1) , '1 ... 3 4 5 ... 8') | |
| self.assertEqual( make_paginator(4,8,0,8) , '1 2 3 4 5 6 7 8') | |
| if __name__ == '__main__': | |
| unittest.main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment