Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

JavaScript - how to calculate page number when we know size of page and item index?

0 contributions
2 points

In this article, we're going to have a look at how in JavaScript, calculate page number on which is item when we know:

  • size of page,
  • item index.

Simple example:

// ONLINE-RUNNER:browser;

function calculatePageNumber(pageSize, itemIndex) {
  return Math.ceil(++itemIndex / pageSize);
};

// Example usage:

var pageSize = 10;
var itemIndex = 29;
var pageNumber = calculatePageNumber(pageSize, itemIndex);

console.log('pageNumber=' + pageNumber); // 3

// Result explanation:
//   page 1 -> indexes from 0 to 9
//   page 2 -> indexes from 10 to 19
//   page 3 -> indexes from 20 to 29
//   etc.

Example tests:

// ONLINE-RUNNER:browser;

function calculatePageNumber(pageSize, itemIndex) {
  return Math.ceil(++itemIndex / pageSize);
};

// Exmaple tests:

var pageSize = 10;
var testingData = [
    { itemIndex:    0, expectedPagesNumber:   1 },
    { itemIndex:    1, expectedPagesNumber:   1 },
    { itemIndex:    9, expectedPagesNumber:   1 },
    { itemIndex:   10, expectedPagesNumber:   2 },
    { itemIndex:   11, expectedPagesNumber:   2 }
];

for (var i = 0; i < testingData.length; ++i) {
    var entry = testingData[i];

    var expected = entry.expectedPagesNumber;
    var actual = calculatePageNumber(pageSize, entry.itemIndex);
    
    var print = (expected === actual ? console.log : console.error);
  	print(expected + ' === ' + actual);
}

 

0 contributions

Suggested wiki articles:

Suggested findings

Let's do the work and have some fun
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way. ❤ 💻 🙂
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    we will help you. 👍 ✔ 🦄
Read more