Skip to content

Instantly share code, notes, and snippets.

@sagittaracc
Last active July 24, 2020 14:24
Show Gist options
  • Save sagittaracc/6042b6230784b7de995bbb283c18d941 to your computer and use it in GitHub Desktop.
Save sagittaracc/6042b6230784b7de995bbb283c18d941 to your computer and use it in GitHub Desktop.
Simple pagination with three dots
function Pagination(countPages, maxLength) {
if (maxLength < 5) return;
if (countPages < maxLength) maxLength = countPages;
this.countPages = countPages;
this.maxLength = maxLength;
this.currentLength = 0;
this.currentPage = this.firstPage = 1;
this.lastPage = this.countPages;
this.pages = [];
}
Pagination.prototype.setCurrentPage = function(number) {
if (number <= this.countPages)
this.currentPage = number;
return this;
};
Pagination.prototype.generate = function() {
this.pages = (new Array(this.countPages)).fill(null);
this.currentLength = 0;
this.stretchWith(this.firstPage);
this.stretchWith(this.lastPage);
this.stretchWith(this.currentPage);
var delta = 1;
while (true) {
if (this.stretchWith(this.currentPage - delta)) break;
if (this.stretchWith(this.currentPage + delta)) break;
delta++;
if (this.currentPage - delta <= this.firstPage && this.currentPage + delta >= this.lastPage) break;
}
return this.pages.join(' ').replace(/\s\s+/g, ' ... ').split(' ');
};
Pagination.prototype.stretchWith = function(pageNumber) {
if (this.pages[pageNumber - 1] === null) {
this.pages[pageNumber - 1] = pageNumber;
this.currentLength++;
}
return this.currentLength === this.maxLength;
};
/*
* Tests:
* (new Pagination(100, 10)).setCurrentPage(1).generate() -> ["1", "2", "3", "4", "5", "6", "7", "8", "9", "...", "100"]
* (new Pagination(100, 10)).setCurrentPage(5).generate() -> ["1", "2", "3", "4", "5", "6", "7", "8", "9", "...", "100"]
* (new Pagination(100, 10)).setCurrentPage(17).generate() -> ["1", "...", "13", "14", "15", "16", "17", "18", "19", "20", "...", "100"]
* (new Pagination(100, 10)).setCurrentPage(24).generate() -> ["1", "...", "20", "21", "22", "23", "24", "25", "26", "27", "...", "100"]
* (new Pagination(100, 10)).setCurrentPage(49).generate() -> ["1", "...", "45", "46", "47", "48", "49", "50", "51", "52", "...", "100"]
* (new Pagination(100, 10)).setCurrentPage(66).generate() -> ["1", "...", "62", "63", "64", "65", "66", "67", "68", "69", "...", "100"]
* (new Pagination(100, 10)).setCurrentPage(78).generate() -> ["1", "...", "74", "75", "76", "77", "78", "79", "80", "81", "...", "100"]
* (new Pagination(100, 10)).setCurrentPage(81).generate() -> ["1", "...", "77", "78", "79", "80", "81", "82", "83", "84", "...", "100"]
* (new Pagination(100, 10)).setCurrentPage(100).generate() -> ["1", "...", "92", "93", "94", "95", "96", "97", "98", "99", "100"]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment