user874737
user874737

Reputation: 533

Pagination next and previous for embed discord js

I have an array that I need to divide into pages with each page showing 4 numbers. I need help on the Next and Previous page commands.

There's an answer about this before in here: How to separate my array into some parts in discord.js?, but I couldn't make it work. Using splice modifies the original array and rearranges the index so the formula there of currentPage * pageSize - pageSize for the next page start index isn't working properly.

Here are the variables for my pagination

let numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let currentPage = 1;
let pageSize = 4;
const countPages = Math.ceil(input.length / pageSize);

Here's the code to show the initial page which shows 1, 2, 3, 4

numberArray.splice(0, pageSize);

Here's the code for Next but this outputs 9, 10, 11, 12.

const nextPage = currentPage + 1;
if (nextPage <= countPages) {
    currentPage = nextPage;
    const startIndex = currentPage * pageSize - pageSize;
    numberArray.splice(startIndex, pageSize)
}

Upvotes: 1

Views: 486

Answers (1)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23160

You shouldn't use splice as it modifies the original array. Although you already know this, you can run the following snippet and see how splice removed those four items from the original array:

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let pageContent = array.splice(4, 4)

console.log('pageContent:', pageContent.toString())
console.log('array:', array.toString())

You could use slice instead that returns a new array:

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let pageContent = array.slice(4, 8)

console.log('pageContent:', pageContent.toString())
console.log('array:', array.toString())

You could also create a class for this:

class Paginator {
  constructor(array, pageSize) {
    this.array = array;
    this.pageSize = pageSize;
    this.currentPage = 1;
  }

  getPage() {
    const startIndex = (this.currentPage - 1) * this.pageSize;
    return this.array.slice(startIndex, startIndex + this.pageSize);
  }

  next() {
    if (this.currentPage * this.pageSize < this.array.length) {
      this.currentPage += 1;
    }
    return this.getPage();
  }

  previous() {
    if (this.currentPage > 1) {
      this.currentPage -= 1;
    }
    return this.getPage();
  }

  first() {
    this.currentPage = 1;
    return this.getPage();
  }

  last() {
    this.currentPage = Math.ceil(this.array.length / this.pageSize);
    return this.getPage();
  }
}

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let pageSize = 4
let paginator = new Paginator(array, pageSize)
console.log(`
  First: ${paginator.first()}
  Next: ${paginator.next()}
  Next: ${paginator.next()}
  Previous: ${paginator.previous()}
  Last: ${paginator.last()}
`)

Upvotes: 1

Related Questions