Skip to content

Instantly share code, notes, and snippets.

@belozerskiy
Last active October 15, 2018 20:53
Show Gist options
  • Save belozerskiy/f9dd66c23b3d559a267c56853e57192c to your computer and use it in GitHub Desktop.
Save belozerskiy/f9dd66c23b3d559a267c56853e57192c to your computer and use it in GitHub Desktop.
pagination with offset - example: 1...45[6]78...10
// example show in string, this script can be adopted to any other output format
const first = 1 // firs item
const current = 5 // current item
const last = 10 // total items
// init offsets
let startLeftOffset = 1
let endLeftOffset = 1
let startRightOffset = 1
let endRightOffset = 1
// first and last item output always
// startLeftOffset set to second
// endLeftOffset set to current
if(current >= 2 && current <= 4) {
startLeftOffset = first + 1
endLeftOffset = current
}
// if current more then 4 extract offset from current and save to startLeftOffset
if(current > 4) {
startLeftOffset = current - 2
endLeftOffset = current
}
let str = ''
if(first !== current) str = first + ' '
for(let start = startLeftOffset; start < endLeftOffset; start++) {
str += start + ' '
}
str += '[' + current + '] '
if(current >= 1 && current <= last - 3) {
startRightOffset = current + 1
endRightOffset = last - (last - startRightOffset) + 1
}
if(current > last - 4) {
startRightOffset = current + 1
endRightOffset = last - 1
}
for(let start = startRightOffset; start <= endRightOffset; start++) {
str += start + ' '
}
if(current !== last) str += last
console.log(str)
@belozerskiy
Copy link
Author

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