A Pen by Kostas Siabanis on CodePen.
Created
August 31, 2015 13:16
-
-
Save ksiabani/aaaa0034c5f0c8858824 to your computer and use it in GitHub Desktop.
Create a simple pagination helper
This file contains hidden or 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
| // 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