Skip to content

Instantly share code, notes, and snippets.

@dehamzah
Created January 22, 2018 13:41
Show Gist options
  • Save dehamzah/d2d780dcde402a194421e7784f8cb294 to your computer and use it in GitHub Desktop.
Save dehamzah/d2d780dcde402a194421e7784f8cb294 to your computer and use it in GitHub Desktop.
Pagination like github
function getDisplayedPages(currentPage, pagesArr) {
/*
Will return 5 total pages, with current page in the middle.
*/
var lastPage = pagesArr.length;
var first = (Math.sign(currentPage - 3) === -1) ? 0 : currentPage - 3;
var last = currentPage + 2;
if (currentPage > lastPage) return;
if (last <= 5) {
last = 5;
}
if (last >= lastPage) {
first = first - (last - lastPage);
last = lastPage;
}
console.log('currentPage', currentPage);
console.log('first', first);
console.log('last', last);
return pagesArr.slice(first, last);
}
var currentPage = 7;
var pagesArr = [1,2,3,4,5,6,7,8,9,10];
var displayedPages = getDisplayedPages(currentPage, pagesArr);
console.log(displayedPages);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment