I made a pagination algorithm but in my opinion it is too complicated and it is quite difficult to be understood. This algorithm should show 5 pages where in the middle is the current page. It should also show two pages before and two pages after the selected page (if these pages exist).
So, I just want to generate the array which is underlined in the above picture.
Here is my code:
public class Pagination {
private int totalPages;
private int selectedPage;
private int offset;
public Pagination() {
totalPages = 6;
selectedPage = 4;
offset = 5;
}
public static void main(String[] args) {
Pagination pagination = new Pagination();
System.out.println(pagination.buildPaginationConditions().toString());
}
private List<Integer> buildPaginationConditions() {
if (selectedPage <= offset / 2) {
return doShowFirstPages();
}
return buildPagination();
}
private List<Integer> doShowFirstPages() {
List<Integer> pagination = new LinkedList<Integer>();
for (int i = 1; i <= offset; i++) {
if (totalPages >= i) {
pagination.add(i);
}
}
return pagination;
}
private List<Integer> buildPagination() {
List<Integer> pagination = new LinkedList<Integer>();
int delta = offset / 2; // How many pages to left/right
int paginationMiddle = (int) Math.ceil((double) offset / 2);
for (int i = 1; i <= offset; i++) {
if (i < paginationMiddle) {
pagination.add(selectedPage - delta);
delta--;
continue;
}
if (paginationMiddle == i) {
pagination.add(selectedPage);
delta = 1;
continue;
}
if (totalPages >= selectedPage + delta) {
pagination.add(selectedPage + delta);
delta++;
continue;
}
if (selectedPage >= totalPages - 1) {
//If it is the last or the penultimate page shift the pages to the right woth 1/2 positions
int noOfGapsInPagination = offset - pagination.size();
int temp = new Integer(offset);
for (int j = 0; j < noOfGapsInPagination; j++) {
pagination.add(j, totalPages - (--temp));
}
break;
}
}
return pagination;
}
}
The algorithm works but I want to write that for loop
from buildPagination()
much more simpler because it looks too complicated now .
I know that I can to extract those pices of code from if conditions
in smaller methods but it is not going to simplify the code to much. Do you have any suggestions?