Skip to content

Instantly share code, notes, and snippets.

@GeroSalas
Created May 1, 2018 21:59
Show Gist options
  • Save GeroSalas/5ab496799e6505dd2bb5143d58950937 to your computer and use it in GitHub Desktop.
Save GeroSalas/5ab496799e6505dd2bb5143d58950937 to your computer and use it in GitHub Desktop.
Paginator Helper
// Paginator Helper Class
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) {
if (isNaN(pageIndex) || pageIndex < 0 || pageIndex >= this.pageCount()) {
return -1
}
if (pageIndex === this.pageCount() - 1) {
const itemsOffset = pageIndex * this.itemsPerPage
return this.itemCount() - itemsOffset
}
if (pageIndex < this.pageCount() - 1) {
return this.itemsPerPage
}
}
pageIndex(itemIndex) {
if (isNaN(itemIndex) || itemIndex < 0 || itemIndex >= this.itemCount()) {
return -1
}
return Math.floor(itemIndex / this.itemsPerPage)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment