Created
January 15, 2019 22:00
-
-
Save SimplyComplexable/b18dd9222d137570328ced70346d33dc to your computer and use it in GitHub Desktop.
Pagination active pages resolver
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
const getActivePages = ({ activePage = 1, pageListLength, pages }) => { | |
const pageCount = pages < pageListLength ? pages : pageListLength; | |
const array = Array.from({ length: pageCount }); | |
const middle = Math.ceil(pageCount / 2); | |
// When the page number is less than the median of the displayed pages, show first n pages | |
if (activePage < middle) { | |
return array.map((_, index) => index + 1); | |
} | |
// When the page number is more than the median of the displayed pages, show last n pages | |
if (pages - activePage < middle) { | |
return array.map((_, index) => pages - index).reverse(); | |
} | |
// Otherwise show page numbers centered around activePage | |
return array.map( | |
(_, index) => index + activePage - middle + (pageCount % 2) + 1, | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment