Last active
September 16, 2023 21:53
-
-
Save gorkemozkan/b36d7948cea63fa3fd862e2fc5816e7e to your computer and use it in GitHub Desktop.
Pagination Helper
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
class PaginationHelper { | |
constructor(collection, itemsPerPage) { | |
this.collection = collection; | |
this.itemsPerPage = itemsPerPage; | |
} | |
itemCount() { | |
return this.collection.length; | |
} | |
pageCount() { | |
return Math.ceil(this.itemCount() / this.itemsPerPage); | |
} | |
pageItemCount(pageIndex) { | |
const pages = this.createPagination(); | |
return pages[pageIndex]?.length ?? -1; | |
} | |
pageIndex(itemIndex) { | |
if (itemIndex < 0 || itemIndex >= this.itemCount()) { | |
return -1; | |
} | |
return Math.floor(itemIndex / this.itemsPerPage); | |
} | |
createPagination() { | |
const pages = []; | |
const pageCount = this.pageCount(); | |
const collection = [...this.collection]; | |
for (let i = 0; i < pageCount; i++) { | |
pages.push(collection.splice(0, this.itemsPerPage)); | |
} | |
return pages; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment