Класс пагинатор

Credit: http://www.codewars.com/kata/paginationhelper/train/javascript

by Artem

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.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) {
	if (pageIndex + 1 > this.pageCount()) return -1;
  if (pageIndex + 1 == this.pageCount()) return this.itemCount() % this.itemsPerPage;
  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) {
	if (itemIndex + 1 > this.itemCount() || itemIndex < 0) return -1;
  let page = this.itemsPerPage;
  let pageIndex = 1;
  while(true) {
		page = page / itemIndex;
    if (page > 1) break; 
    pageIndex++;
    page = this.itemsPerPage * pageIndex;
  }
  return pageIndex - 1;
}

var helper = new PaginationHelper(['a','b','c','d','e','f'], 4);
helper.pageCount(); //should == 2
helper.itemCount(); //should == 6
helper.pageItemCount(0); //should == 4
helper.pageItemCount(1); // last page - should == 2
helper.pageItemCount(2); // should == -1 since the page is invalid

console.log(helper.pageIndex(5)); //should == 1 (zero based index)
console.log(helper.pageIndex(2)); //should == 0
console.log(helper.pageIndex(20)); //should == -1
console.log(helper.pageIndex(-10)); //should == -1