Skip to content

Instantly share code, notes, and snippets.

@gorkemozkan
Last active September 16, 2023 21:53
Show Gist options
  • Save gorkemozkan/b36d7948cea63fa3fd862e2fc5816e7e to your computer and use it in GitHub Desktop.
Save gorkemozkan/b36d7948cea63fa3fd862e2fc5816e7e to your computer and use it in GitHub Desktop.
Pagination Helper
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