Last active
October 1, 2018 18:34
-
-
Save gerarldlee/7a8fdecf7149d355203248c037c9d502 to your computer and use it in GitHub Desktop.
For this exercise you will complete the PaginationHelper class, which is a utility class helpful for querying paging information related to an array.
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
# | |
# I have to admit this is my first time using ruby and I find the syntax very easy and appealing. | |
# | |
# A simple PaginationHelper utility class | |
# | |
# Gerard Lee <[email protected]> | |
# Oct 1, 2018 | |
class PaginationHelper | |
# declare global variable here that holds collection array and item per page | |
$collection = Array.new # im not sure if this is necessary in ruby, | |
# in java you have to declare before anything else | |
$items_per_page = 0 | |
# The constructor takes in an array of items and a integer indicating how many | |
# items fit within a single page | |
def initialize(collection, items_per_page) | |
# assign collection and item per page to the global variable | |
$collection = collection | |
$items_per_page = items_per_page | |
end | |
# returns the number of items within the entire collection | |
def item_count | |
# return is not necessary, but being explicit about it is good | |
return $collection.length | |
end | |
# returns the number of pages | |
def page_count | |
# by dividing collections.lenth over the items per page, we get the page count | |
# round up to the nearest whole number | |
return ($collection.length / $items_per_page.to_f).ceil | |
end | |
# returns the number of items on the current page. page_index is zero based. | |
# this method should return -1 for page_index values that are out of range | |
def page_item_count(page_index) | |
if ((page_index < 0) || (page_index >= page_count())) | |
return -1 | |
end | |
if (page_index < page_count() - 1) | |
return $items_per_page | |
end | |
last_page_count = ($collection.length % $items_per_page) | |
return last_page_count | |
end | |
# determines what page an item is on. Zero based indexes. | |
# this method should return -1 for item_index values that are out of range | |
def page_index(item_index) | |
# if item_index is in out of scope, then return -1 | |
if ((item_index < 0) || (item_index >= item_count())) | |
return -1 | |
end | |
# item_index will be therefore in scope, just divide by items_per_page and get the floor | |
return (item_index / $items_per_page.to_f).floor | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment