Skip to content

Instantly share code, notes, and snippets.

@proudlygeek
Created July 15, 2014 11:17
Show Gist options
  • Save proudlygeek/db851215b8f10b154f4d to your computer and use it in GitHub Desktop.
Save proudlygeek/db851215b8f10b154f4d to your computer and use it in GitHub Desktop.
Pagination Helper Kata
// http://www.codewars.com/kata/515bb423de843ea99400000a/train/javascript
// TODO: complete this object/class
// 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.items = collection;
this.itemsPerPage = itemsPerPage;
}
// returns the number of items within the entire collection
PaginationHelper.prototype.itemCount = function() {
return this.items.length;
}
// returns the number of pages
PaginationHelper.prototype.pageCount = function() {
return Math.ceil(this.itemCount() / 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) {
var itemsPerPage = this.itemsPerPage,
itemCount = this.itemCount(),
pageCount = this.pageCount();
if (pageIndex >= pageCount || pageIndex < 0) return -1;
return this.items.slice(pageIndex * itemsPerPage, itemCount).splice(0, itemsPerPage).length;
}
// 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) {
if (this.itemCount() === 0
|| itemIndex < 0
|| itemIndex > this.itemCount()) return -1;
if (itemIndex === 0
|| itemIndex / this.itemsPerPage === 1) return 0;
return Math.floor((itemIndex / this.itemsPerPage));
}
// Create your own tests here. These are some of the methods available:
// Test.expect(boolean, [optional] message)
// Test.assertEquals(actual, expected, [optional] message)
// Test.assertSimilar(actual, expected, [optional] message)
// Test.assertNotEquals(actual, expected, [optional] message)
var helper = new PaginationHelper(['a','b','c','d','e','f'], 4);
Test.assertEquals(helper.itemCount(), 6);
Test.assertEquals(helper.pageCount(), 2);
Test.assertEquals(helper.pageItemCount(0), 4);
Test.assertEquals(helper.pageItemCount(1), 2);
Test.assertEquals(helper.pageItemCount(2), -1);
Test.assertEquals(helper.pageItemCount(-10), -1);
Test.assertEquals(helper.pageIndex(5), 1);
Test.assertEquals(helper.pageIndex(6), 1);
Test.assertEquals(helper.pageIndex(2), 0);
Test.assertEquals(helper.pageIndex(4), 0);
Test.assertEquals(helper.pageIndex(6), 1);
Test.assertEquals(helper.pageIndex(-10), -1);
Test.assertEquals(helper.pageIndex(7), -1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment