Last active
April 1, 2020 13:20
-
-
Save LauraBeatris/af71051d20453c5a55eed976e47e748a to your computer and use it in GitHub Desktop.
Options of Pagination Algorithms with JavaScript
This file contains 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
/* First Example */ | |
function pagination( | |
totalItems, | |
selectedPage, | |
itemsLimit = 4, | |
){ | |
// Calculating the total of pages by dividing the limit and the numbers of items | |
const totalPages = Math.ceil(totalItems / itemsLimit); | |
const startPage = 1; | |
const endPage = totalPages; | |
// Veryfing if the current page isn't out of range | |
if (selectedPage < 0) { | |
selectedPage = 1; | |
} else if (selectedPage > totalPages) { | |
selectedPage = totalPages; | |
} | |
let delta = 2, | |
left = selectedPage - delta, | |
right = selectedPage + delta, | |
lastPage = null, | |
pages = []; | |
for (let currentPage = 1; currentPage <= totalPages; currentPage++){ | |
// Adding the first, last and intermediary pages | |
if (currentPage === 1 || currentPage === totalPages || (currentPage >= left && currentPage <= right)) { | |
if (lastPage && (currentPage - lastPage) >= 2) { | |
pages.push('...') | |
} | |
pages.push(currentPage) | |
lastPage = currentPage | |
} | |
} | |
return pages; | |
} | |
/* Second Example - Without dots */ | |
function paginationWithoutPages( | |
totalItems, | |
selectedPage, | |
itemsLimit = 4 | |
) { | |
// Calculating the total of pages by dividing the limit and the numbers of items | |
const totalPages = Math.ceil(totalItems / itemsLimit) | |
const delta = 2; | |
const left = selectedPage - delta; | |
const right = selectedPage + delta; | |
let pages = []; | |
pages = Array.from({length: totalPages}, (value, key) => key + 1) | |
.filter(page => page && page >= left && page <= right) | |
return pages; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment