Skip to content

Instantly share code, notes, and snippets.

@qbein
Last active January 14, 2017 08:51
Show Gist options
  • Save qbein/6032591 to your computer and use it in GitHub Desktop.
Save qbein/6032591 to your computer and use it in GitHub Desktop.
Simple pagination function
function getPages(pageCount, current, padding, boundaryPadding) {
var start, end, pages;
start = current - padding;
end = current + padding;
if (start < 0) {
end += Math.abs(start) + 1;
}
if (end > pageCount) {
start -= end - pageCount;
}
pages = [];
function pushPage(num) {
pages.push({
link: true,
num: num,
label: num
});
}
function pushEllipsis() {
pages.push({
ellipsis: true,
label: '...'
});
}
function pushCurrent(num) {
pages.push({
num: num,
current: true,
label: num
});
}
for (var i = 1; i <= pageCount; i++) {
if (i > boundaryPadding && i < start - 1) {
continue;
}
if (i > end + 1 && i <= pageCount - boundaryPadding) {
continue;
}
if (i == start - 1 && start - 2 > boundaryPadding) {
pushEllipsis();
continue;
}
if (i == end + 1 && end + 1 < pageCount - boundaryPadding) {
pushEllipsis();
continue;
}
if (i == current) {
pushCurrent(i);
continue;
}
pushPage(i);
}
return pages;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment