|
| 1 | +# TODO: complete this class |
| 2 | + |
| 3 | +class PaginationHelper |
| 4 | + |
| 5 | + # The constructor takes in an array of items and a integer indicating how many |
| 6 | + # items fit within a single page |
| 7 | + def initialize(collection, items_per_page) |
| 8 | + @items_per_page = items_per_page |
| 9 | + @pages = Array.new(collection.count.fdiv(items_per_page).ceil) do |i| |
| 10 | + Array.new() |
| 11 | + end |
| 12 | + page_number = 0 |
| 13 | + until collection.empty? |
| 14 | + @items_per_page.times do |item_number| |
| 15 | + @pages[page_number][item_number] = collection.shift |
| 16 | + break if collection.empty? |
| 17 | + end |
| 18 | + page_number += 1 |
| 19 | + end |
| 20 | + end |
| 21 | + |
| 22 | + # returns the number of items within the entire collection |
| 23 | + def item_count |
| 24 | + @pages.inject(0){|item_count, page| item_count + page.count} |
| 25 | + end |
| 26 | + |
| 27 | + # returns the number of pages |
| 28 | + def page_count |
| 29 | + @pages.count |
| 30 | + end |
| 31 | + |
| 32 | + # returns the number of items on the current page. page_index is zero based. |
| 33 | + # this method should return -1 for page_index values that are out of range |
| 34 | + def page_item_count(page_index) |
| 35 | + return -1 if page_index < 0 || page_index >= self.page_count |
| 36 | + @pages[page_index].count |
| 37 | + end |
| 38 | + |
| 39 | + # determines what page an item is on. Zero based indexes. |
| 40 | + # this method should return -1 for item_index values that are out of range |
| 41 | + def page_index(item_index) |
| 42 | + return -1 if item_index < 0 || item_index >= self.item_count |
| 43 | + location = item_index.divmod @items_per_page |
| 44 | + location[0] |
| 45 | + end |
| 46 | +end |
| 47 | + |
| 48 | +helper = PaginationHelper.new(['a','b','c','d','e','f'], 4) |
| 49 | +puts helper.page_count # should == 2 |
| 50 | +puts helper.item_count # should == 6 |
| 51 | +puts helper.page_item_count(0) # should == 4 |
| 52 | +puts helper.page_item_count(1) # last page - should == 2 |
| 53 | +puts helper.page_item_count(2) # should == -1 since the page is invalid |
| 54 | + |
| 55 | +# page_ndex takes an item index and returns the page that it belongs on |
| 56 | +puts helper.page_index(5) # should == 1 (zero based index) |
| 57 | +puts helper.page_index(2) # should == 0 |
| 58 | +puts helper.page_index(20) # should == -1 |
| 59 | +puts helper.page_index(-10) # should == -1 because negative indexes are invalid |
0 commit comments