Skip to content

Instantly share code, notes, and snippets.

@williammustaffa
Created October 22, 2020 17:39
Show Gist options
  • Save williammustaffa/7cd5348bd75fc6f5238106b9a6f2bd6c to your computer and use it in GitHub Desktop.
Save williammustaffa/7cd5348bd75fc6f5238106b9a6f2bd6c to your computer and use it in GitHub Desktop.
Simple pagination algorithm using lodash
import first from 'lodash/first'
import last from 'lodash/last'
import inRange from 'lodash/inRange'
export function createPagination(items, current, delta) {
const currentIndex = items.indexOf(current)
const left = currentIndex - delta
const right = currentIndex + delta + 1
const applyDots = (data, item, lastItem) => {
const diff = item - lastItem
if (diff === 2) {
data.push(lastItem + 1)
} else if (diff !== 1) {
data.push('...')
}
return data
}
const pagination = items
.filter((item, index) => {
return (
item === first(items) ||
item === last(items) ||
inRange(index, left, right)
)
})
.reduce((data, item) => {
const lastItem = last(data)
if (lastItem) {
applyDots(data, item, lastItem)
}
data.push(item)
return data
}, [])
return pagination
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment