CodeWars: Pagination Helper Solution

1// The constructor takes in an array of items and a integer indicating how many
2// items fit within a single page
3function PaginationHelper(collection, itemsPerPage) {
4 this.collection = collection
5 this.itemsPerPage = itemsPerPage
6}
7
8// returns the number of items within the entire collection
9PaginationHelper.prototype.itemCount = function () {
10 return this.collection.length
11}
12
13// returns the number of pages
14PaginationHelper.prototype.pageCount = function () {
15 return Math.ceil(this.itemCount() / this.itemsPerPage)
16}
17
18// returns the number of items on the current page. page_index is zero based.
19// this method should return -1 for pageIndex values that are out of range
20PaginationHelper.prototype.pageItemCount = function (pageIndex) {
21 if (pageIndex + 1 < this.pageCount()) {
22 return this.itemsPerPage
23 } else if (pageIndex + 1 === this.pageCount()) {
24 return this.itemCount() % this.itemsPerPage
25 }
26 return -1
27}
28
29// determines what page an item is on. Zero based indexes
30// this method should return -1 for itemIndex values that are out of range
31PaginationHelper.prototype.pageIndex = function (itemIndex) {
32 const res = Math.floor(itemIndex / this.itemsPerPage)
33 return 0 <= res && res < this.pageCount() ? res : -1
34}

Comments

Loading comments...

Tags

codewars

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

CodeWars: Moving Zeroes To The End

Feb 3, 2021

Previous Post

HoningJS

Search Posts