-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPaginationHelper.java
59 lines (51 loc) · 1.9 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
package com.company.PaginationHelper;
import com.company.KataDescription;
import java.util.List;
@KataDescription(
name = "PaginationHelper",
Sensei = "jhoffner",
kyu = 5,
link = "https://www.codewars.com/kata/515bb423de843ea99400000a")
public class PaginationHelper<I> {
private final List<I> collection;
private final 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 (collection.size() % itemsPerPage ) > 0 ? (collection.size() / itemsPerPage) + 1 : collection.size() / 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) {
int maxIndex = pageCount() - 1;
if (pageIndex > maxIndex || collection.size() == 0 || pageIndex < 0) return -1;
int itemsOnLastPage = collection.size() % itemsPerPage;
return pageIndex == collection.size() / itemsPerPage ? itemsOnLastPage : 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) {
if (collection.size() <= 0 || itemIndex < 0 || itemIndex >= collection.size()) return -1;
if (itemIndex == 0) return 0;
return itemIndex / itemsPerPage;
}
}