Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ksiabani/aaaa0034c5f0c8858824 to your computer and use it in GitHub Desktop.

Select an option

Save ksiabani/aaaa0034c5f0c8858824 to your computer and use it in GitHub Desktop.
Create a simple pagination helper
// The constructor takes in an array of items and a integer indicating how many
// items fit within a single page
function PaginationHelper(collection, itemsPerPage){
this.collection = collection;
this.itemsPerPage = itemsPerPage;
}
// returns the number of items within the entire collection
PaginationHelper.prototype.itemCount = function() {
return this.collection.length;
}
// returns the number of pages
PaginationHelper.prototype.pageCount = function() {
return Math.ceil(this.collection.length/this.itemsPerPage);
}
// returns the number of items on the current page. page_index is zero based.
// this method should return -1 for pageIndex values that are out of range
PaginationHelper.prototype.pageItemCount = function(pageIndex) {
pageIndex++;
if ( pageIndex == this.pageCount() ) {
return this.itemCount() - ((this.pageCount() - 1) * this.itemsPerPage);
}
else if ( pageIndex > this.pageCount() || pageIndex < 1 ) {
return -1;
}
else {
return this.itemsPerPage;
}
}
// determines what page an item is on. Zero based indexes
// this method should return -1 for itemIndex values that are out of range
PaginationHelper.prototype.pageIndex = function(itemIndex) {
itemIndex++;
if (itemIndex > this.itemCount() || itemIndex < 1) {
return -1;
}
else {
return Math.ceil(itemIndex / this.itemsPerPage) - 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment