Dynamically generating values that proceed in groups of 5

I am working on pagination which works with the following logic:

  if (currentPage > 5 && currentPage < 11) pages = [6, 7, 8, 9, 10];
  if (currentPage > 10 && currentPage < 16) pages = [11, 12, 13, 14, 15];
  if (currentPage > 15 && currentPage < 21) pages = [16, 17, 18, 19, 20];
  if (currentPage > 20 && currentPage < 26) pages = [21, 22, 23, 24, 25];

However, rather than hardcoding these values, I’d like to write a dynamic version of this, as much as is possible. If you notice, there are always five clickable page numbers on each page, represented by the values in the pages array. But I’m unclear on how to accomplish this.

>Solution :

  1. Divide the currentPage by 5.
  2. Round that value up, and subtract 1. This is important because you keep the multiples of 5 at the end.
  3. Create an array of 5 items starting that that (value * 5) + 1, and increment for the length of the array.
function createPageRange(currentPage) {
  const startingPageMultiple = Math.ceil(currentPage / 5) - 1;
  const startingPage = (startingPageMultiple * 5) + 1;
  return Array(5).fill().map((_, i) => i + startingPage);
}

console.log('currentPage = 1', createPageRange(1));
console.log('currentPage = 5', createPageRange(5));
console.log('currentPage = 6', createPageRange(6));
console.log('currentPage = 18', createPageRange(18));
console.log('currentPage = 21', createPageRange(21));

Leave a Reply