Skip to content

Instantly share code, notes, and snippets.

@vedovelli
Created September 11, 2016 08:32
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save vedovelli/9b99e5dfd720ae7b92ab1faaa22474bc to your computer and use it in GitHub Desktop.
Save vedovelli/9b99e5dfd720ae7b92ab1faaa22474bc to your computer and use it in GitHub Desktop.
generatePagesArray: function(currentPage, collectionLength, rowsPerPage, paginationRange)
{
var pages = [];
var totalPages = Math.ceil(collectionLength / rowsPerPage);
var halfWay = Math.ceil(paginationRange / 2);
var position;
if (currentPage <= halfWay) {
position = 'start';
} else if (totalPages - halfWay < currentPage) {
position = 'end';
} else {
position = 'middle';
}
var ellipsesNeeded = paginationRange < totalPages;
var i = 1;
while (i <= totalPages && i <= paginationRange) {
var pageNumber = this.calculatePageNumber(i, currentPage, paginationRange, totalPages);
var openingEllipsesNeeded = (i === 2 && (position === 'middle' || position === 'end'));
var closingEllipsesNeeded = (i === paginationRange - 1 && (position === 'middle' || position === 'start'));
if (ellipsesNeeded && (openingEllipsesNeeded || closingEllipsesNeeded)) {
pages.push('...');
} else {
pages.push(pageNumber);
}
i ++;
}
return pages;
},
calculatePageNumber: function(i, currentPage, paginationRange, totalPages)
{
var halfWay = Math.ceil(paginationRange/2);
if (i === paginationRange) {
return totalPages;
} else if (i === 1) {
return i;
} else if (paginationRange < totalPages) {
if (totalPages - halfWay < currentPage) {
return totalPages - paginationRange + i;
} else if (halfWay < currentPage) {
return currentPage - halfWay + i;
} else {
return i;
}
} else {
return i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment