Skip to content

Instantly share code, notes, and snippets.

@keon
Last active March 24, 2021 06:16
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save keon/5380f81393ad98ec19e6 to your computer and use it in GitHub Desktop.
Save keon/5380f81393ad98ec19e6 to your computer and use it in GitHub Desktop.
javascript pagination algorithm
var pagenation = function(current, total){
var list = [];
var pageLimit = 5;
var upperLimit, lowerLimit;
var currentPage = lowerLimit = upperLimit = Math.min(current, total);
for (var b = 1; b < pageLimit && b < total;) {
if (lowerLimit > 1 ) {
lowerLimit--; b++;
}
if (b < pageLimit && upperLimit < total) {
upperLimit++; b++;
}
}
for (var i = lowerLimit; i <= upperLimit; i++) {
if (i == currentPage){
list.push("["+i+"]");
}
else{
list.push(i);
}
}
console.log(list);
return list;
}
@gr8pathik
Copy link

Awesome code. Just found small one bug.

it is not working with var pageLimit = 2;

for page 1 it is giving Selected page 1: (2) ["[1]", 2] and also for page 2 it is giving the same Selected page 2: (2) [1, "[2]"] because of this user cannot go to the third page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment