Last active
March 24, 2021 06:16
-
-
Save keon/5380f81393ad98ec19e6 to your computer and use it in GitHub Desktop.
javascript pagination algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Awesome thank you for sharing :D
Just to let other people know what this function returns:
Selected page 1: ["[1]", 2, 3, 4, 5]
Selected page 2: [1, "[2]", 3, 4, 5]
Selected page 3: [1, 2, "[3]", 4, 5]
Selected page 4: [2, 3, "[4]", 5, 6]
Selected page 5: [3, 4, "[5]", 6, 7]
Selected page 6: [4, 5, "[6]", 7, 8]
Selected page 7: [5, 6, "[7]", 8, 9]
Selected page 8: [6, 7, "[8]", 9, 10]
Selected page 9: [7, 8, "[9]", 10, 11]
Selected page 10: [8, 9, "[10]", 11, 12]
Selected page 11: [9, 10, "[11]", 12, 13]
Selected page 12: [10, 11, "[12]", 13, 14]
Selected page 13: [11, 12, "[13]", 14, 15]
Selected page 14: [12, 13, "[14]", 15, 16]
Selected page 15: [13, 14, "[15]", 16, 17]
Selected page 16: [14, 15, "[16]", 17, 18]
Selected page 17: [15, 16, "[17]", 18, 19]
Selected page 18: [16, 17, "[18]", 19, 20]
Selected page 19: [16, 17, 18, "[19]", 20]
Selected page 20: [16, 17, 18, 19, "[20]"]
for (let i = 1; i <= 20; i++)
console.log(`Selected page ${i}:`, pagenation(i, 20));
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
Why didn't you use nested loops, and have it break on max posts, or if there are no more posts? Good algorithm though