我正在尝试解决在Edabit上发布的挑战,并且遇到了我不太熟悉的情况。这是挑战所需的测试之一:
const ids = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // good so far
const p2 = new Pagination(ids, 5); // good so far
p2.getVisibleItems(); // good so far
p2.nextPage().getVisibleItems(); // what's going on here?
我可以猜测一下,这可能是连接函数的一种方式……虽然很有意义,但我不知道该怎么做。
这是我到目前为止所完成的。
class Pagination {
constructor(items, pageSize) {
this.items = items; // Holds the items array
this.pageSize = pageSize; // Holds the size of each page
this.totalPages = items.length; // Holds the total number of pages
this.currentPage = 0; // Holds the current page number
this.dicPages = {};
}
// Methods
// Goes to the previous page
prevPage() {
this.currentPage = this.currentPage - this.pageSize;
if (this.currentPage < 0) {
this.currentPage = 0;
}
return this.getVisibleItems();
}
// Goes to the next page
nextPage() {
this.currentPage = this.currentPage + this.pageSize;
return this.getVisibleItems();
}
// Goes to the first page
firstPage() {
this.currentPage = 0;
return this.getVisibleItems();
}
// Goes to the last page
lastPage() {
var pageIndex = (Object.keys(this.dicPages).length - 1) * this.pageSize;
this.currentPage = pageIndex;
return this.getVisibleItems();
}
// Goes to a page determined by the `page` argument
goToPage(page) {
this.currentPage = page;
return this.getVisibleItems();
}
// Returns the currently visible items as an array
getVisibleItems() {
var j = 0;
for (var i = 0, j = this.items.length; i < j; i += this.pageSize) {
this.dicPages[i] = this.items.slice(i, i + this.pageSize);
}
return this.dicPages[this.currentPage];
}
}
const ids = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const p2 = new Pagination(ids, 5);
console.log(p2.getVisibleItems()); //, [0, 1, 2, 3, 4]
console.log(p2.nextPage().getVisibleItems()); //, [5, 6, 7, 8, 9]
console.log(p2.nextPage().getVisibleItems()); //, [10]