Created
October 22, 2020 17:39
-
-
Save williammustaffa/7cd5348bd75fc6f5238106b9a6f2bd6c to your computer and use it in GitHub Desktop.
Simple pagination algorithm using lodash
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
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