-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPaginationHelper.java
71 lines (63 loc) · 2.49 KB
/
PaginationHelper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package me.m_zebrak.kyu5;
import java.util.List;
/**
* For this exercise you will be strengthening your page-fu mastery. You will complete the PaginationHelper class,
* which is a utility class helpful for querying paging information related to an array.
* <p>
* The class is designed to take in an array of values and an integer indicating how many items will be allowed per
* each page. The types of values contained within the collection/array are not relevant.
* <p>
* The following are some examples of how this class is used:
* <p>
* PaginationHelper<Character> helper = new PaginationHelper(Arrays.asList('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
* <p>
* // pageIndex takes an item index and returns the page that it belongs on
* helper.pageIndex(5); //should == 1 (zero based index)
* helper.pageIndex(2); //should == 0
* helper.pageIndex(20); //should == -1
* helper.pageIndex(-10); //should == -1
*/
public class PaginationHelper<I> {
private List<I> collection;
private int itemsPerPage;
/**
* The constructor takes in an array of items and a integer indicating how many
* items fit within a single page
*/
public PaginationHelper(List<I> collection, int itemsPerPage) {
this.collection = collection;
this.itemsPerPage = itemsPerPage;
}
/**
* returns the number of items within the entire collection
*/
public int itemCount() {
return collection.size();
}
/**
* returns the number of pages
*/
public int pageCount() {
return (int) Math.ceil((float) itemCount() / 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
*/
public int pageItemCount(int pageIndex) {
return (pageIndex >= pageCount() || pageIndex < 0) ? -1 :
(pageIndex == pageCount() - 1) ? itemCount() % itemsPerPage : itemsPerPage;
}
/**
* determines what page an item is on. Zero based indexes
* this method should return -1 for itemIndex values that are out of range
*/
public int pageIndex(int itemIndex) {
return (itemIndex > itemCount() - 1 || itemIndex < 0) ? -1 : itemIndex / itemsPerPage;
}
}