Как объединить функции из класса в JS? - PullRequest
0 голосов
/ 02 июля 2019

Я пытаюсь решить задачу, опубликованную на 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]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...