Skip to content

Instantly share code, notes, and snippets.

@dptole
Last active September 1, 2022 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dptole/139ee24b91b57624fcd64a317e7bfe55 to your computer and use it in GitHub Desktop.
Save dptole/139ee24b91b57624fcd64a317e7bfe55 to your computer and use it in GitHub Desktop.
Nodejs simple pagination
const help = {
genPagination: (pageLength, fullPageSelectedIndex) => {
const fullPage = Array.from(Array(pageLength)).map((v, i) => i)
if (fullPage.length < 11) return fullPage
let minLeftCut = 2
let maxLeftCut = 6
let minRightCut = 2
let maxRightCut = 6
let leftPrefix = 2
let minLeftPrefix = 6
let rightPrefix = 2
let minRightPrefix = 6
let leftSide = fullPage.slice(0, fullPageSelectedIndex)
let rightSide = fullPage.slice(fullPageSelectedIndex + 1)
let selectedValue = fullPage[fullPageSelectedIndex]
if (leftSide.length >= minLeftPrefix) {
let leftCut = maxLeftCut - rightSide.length < minLeftCut ? minLeftCut : maxLeftCut - rightSide.length
leftSide = fullPage.slice(0, leftPrefix).concat(['...']).concat(leftSide.slice(-leftCut))
}
if (rightSide.length >= minRightPrefix) {
let rightCut = maxRightCut - leftSide.length < minRightCut ? minRightCut : maxRightCut - leftSide.length
rightSide = rightSide.slice(0, rightCut).concat(['...']).concat(fullPage.slice(-rightPrefix))
}
return leftSide.concat(selectedValue).concat(rightSide)
},
}
module.exports = help
@dptole
Copy link
Author

dptole commented Sep 1, 2022

// There are 420 pages in total
// The page 69 is currently selected
// Generate the pagination layout
const page = help.genPagination(420, 69)
// First page start at index 0
// page = [0, 1, "...", 67, 68, 69, 70, 71, "...", 418, 419]

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