As part of my daily work, got a task to implement pagination in my react app. I completed the UI and state management but got stuck at the pagination algorithm. I referred to many standard algorithms listed below
- https://gist.github.com/kottenator/9d936eb3e4e3c3e02598
- https://flaviusmatis.github.io/simplePagination.js
The problem is ours is a slightly modified algorithm. What I did is used the algorithm mentioned here - https://gist.github.com/kottenator/9d936eb3e4e3c3e02598 and implemented the basic pagination component with different UI states. (If array[i] === selectedPageFromProps, then highlight that page with different colour
)
What this algorithm does is it will take selectedPage and totalNumberOfPages as an argument and return an array of all pages with an ellipsis (if more pages are there)
function pagination(selectedPage, totalPages) {return arrayOfPageNumbers with Ellipsis(if required)}
The algorithm should return different values based on the device - in mobile, we show a maximum 4 numbers and in desktop, we show maximum of 7 pages.
Different return values for this algorithm mentioned below.
In Mobile - Max number of pages to be displayed is 4
*****************************************************
pagination(1,4) : 1,2,3,4
pagination(2,4) : 1,2,3,4
pagination(3,4) : 1,2,3,4
pagination(4,4) : 1,2,3,4
If totalPages > 4
pagination(1,99) : 1,2,3,...,99
pagination(2,99) : 1,2,3,...,99
pagination(3,99) : 1,...,3,...,99
pagination(4,99) : 1,...,4,...,99
pagination(5,99) : 1,...,5,...,99
pagination(97,99) : 1,...,97,...99
pagination(98,99) : 1,...,98,...99
pagination(99,99) : 1,...,98,99
In Desktop/Tablet - Max number of pages to be displayed is 7
************************************************************
pagination(1,7) : 1,2,3,4,5,6,7
pagination(2,7) : 1,2,3,4,5,6,7
pagination(7,7) : 1,2,3,4,5,6,7
If totalPages > 7
pagination(1,99) : 1,2,3,4,5,6,...,99
pagination(2,99) : 1,2,3,4,5,6,...,99
pagination(4,99) : 1,2,3,4,5,6,...,99
pagination(5,99) : 1,...,3,4,5,6,7,...,99
pagination(95,99) : 1,...,93,94,95,96,97,...,99
pagination(96,99) : 1,...,94,95,96,97,98,...,99
pagination(97,99) : 1,...,95,96,97,98,99
pagination(98,99) : 1,...,95,96,97,98,99
pagination(99,99) : 1,...,95,96,97,98,99
Can someone help me to modify or implement the new algorithm?
Currently I am using the algorithm mentioned below.
function pagination(currentPage, nrOfPages, deltaValue) {
var delta = deltaValue,
range = [],
rangeWithDots = [],
l;
range.push(1);
if (nrOfPages <= 1) {
return range;
}
for (let i = currentPage - delta; i <= currentPage + delta; i++) {
if (i < nrOfPages && i > 1) {
range.push(i);
}
}
range.push(nrOfPages);
for (let i of range) {
if (l) {
if (i - l === 2) {
rangeWithDots.push(l + 1);
} else if (i - l !== 1) {
rangeWithDots.push("...");
}
}
rangeWithDots.push(i);
l = i;
}
return rangeWithDots;
}