Created
November 3, 2021 05:05
-
-
Save MalikBagwala/fe6d92b542ae3fe944e37f435ce69950 to your computer and use it in GitHub Desktop.
A useful utility function to paginate using a page based method
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
export interface PaginationOptions { | |
totalItems: number; | |
currentPage?: number; | |
pageSize?: number; | |
maxPages?: number; | |
} | |
function paginate(options: PaginationOptions) { | |
const totalItems = options.totalItems || 1; | |
let currentPage = options.currentPage || 1; | |
const pageSize = options.pageSize || 10; | |
const maxPages = options.maxPages || 1; | |
// calculate total pages | |
const totalPages = Math.ceil(totalItems / pageSize); | |
// ensure current page isn't out of range | |
if (currentPage < 1) { | |
currentPage = 1; | |
} else if (currentPage > totalPages) { | |
currentPage = totalPages; | |
} | |
let startPage: number, endPage: number; | |
if (totalPages <= maxPages) { | |
// total pages less than max so show all pages | |
startPage = 1; | |
endPage = totalPages; | |
} else { | |
// total pages more than max so calculate start and end pages | |
const maxPagesBeforeCurrentPage = Math.floor(maxPages / 2); | |
const maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1; | |
if (currentPage <= maxPagesBeforeCurrentPage) { | |
// current page near the start | |
startPage = 1; | |
endPage = maxPages; | |
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) { | |
// current page near the end | |
startPage = totalPages - maxPages + 1; | |
endPage = totalPages; | |
} else { | |
// current page somewhere in the middle | |
startPage = currentPage - maxPagesBeforeCurrentPage; | |
endPage = currentPage + maxPagesAfterCurrentPage; | |
} | |
} | |
// calculate start and end item indexes | |
const startIndex = (currentPage - 1) * pageSize; | |
const endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1); | |
// create an array of pages to ng-repeat in the pager control | |
const pages = Array.from(Array(endPage + 1 - startPage).keys()).map((i) => startPage + i); | |
// return object with all pager properties required by the view | |
return { | |
totalItems: totalItems, | |
currentPage: currentPage, | |
pageSize: pageSize, | |
totalPages: totalPages, | |
startPage: startPage, | |
endPage: endPage, | |
startIndex: startIndex, | |
endIndex: endIndex, | |
pages: pages | |
}; | |
} | |
export default paginate; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment