Skip to content

Instantly share code, notes, and snippets.

@thunder775
Last active June 1, 2020 06:52
Show Gist options
  • Save thunder775/f61d36bdbcba9e4356a396d5bf55588e to your computer and use it in GitHub Desktop.
Save thunder775/f61d36bdbcba9e4356a396d5bf55588e to your computer and use it in GitHub Desktop.
class Pagination {
constructor(items = [], pageSize = 10) {
this.pagesArray = this.getPages(items, pageSize);
this.pointer = 0;
}
prevPage() {
if (this.pointer !== 0) {
this.pointer--;
return this;
}
}
firstPage() {
this.pointer = 0
}
gotoPage(toPage = 1) {
if (toPage >= 0 && toPage <= this.pagesArray.length - 1) {
this.pointer = toPage;
}
}
lastPage() {
this.pointer = this.pagesArray.length - 1
}
nextPage() {
if (this.pointer !== this.pagesArray.length - 1) {
this.pointer++;
return this;
}
}
getVisibleItems() {
return this.pagesArray[this.pointer]
}
getPages(items, pageSize) {
let result = [];
let sublist = [];
for (let i = 0; i < items.length; i++) {
sublist.push(items[i]);
if (sublist.length === pageSize) {
result.push(sublist);
sublist = [];
}
}
if (sublist.length !== 0) result.push(sublist);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment