Languages
[Edit]
EN

JavaScript - how to calculate number of pages when we know size of page and total number of items?

4 points
Created by:
Greg
5140

In this article, we're going to have a look at how in JavaScript, calculate number of pages when we know:

  • size of page,
  • total number of items.

Simple example:

// ONLINE-RUNNER:browser;

function calculatePagesCount(pageSize, totalCount) {
  // we suppose that if we have 0 items we want 1 empty page
  return totalCount < pageSize ? 1 : Math.ceil(totalCount / pageSize);
}

// Example usage:

var pageSize = 10;
var itemsCount = 21;
var pagesCount = calculatePagesCount(pageSize, itemsCount);

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

// Result explanation:
//   page 1 -> 10 items
//   page 2 -> 10 items
//   page 3 ->  1 item

Example tests:

// ONLINE-RUNNER:browser;

function calculatePagesCount(pageSize, totalCount) {
  // we suppose that if we have 0 items we want 1 empty page
  return totalCount < pageSize ? 1 : Math.ceil(totalCount / pageSize);
}

// Exmaple tests:

var pageSize = 10;
var testingData = [
    { itemsCount:    0, expectedPagesCount:   1 }, // 1 empty page
    { itemsCount:    1, expectedPagesCount:   1 },
    { itemsCount:   10, expectedPagesCount:   1 },
    { itemsCount:   11, expectedPagesCount:   2 },
    { itemsCount:   99, expectedPagesCount:  10 },
    { itemsCount:  100, expectedPagesCount:  10 },
    { itemsCount:  101, expectedPagesCount:  11 }
];

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

    var expected = entry.expectedPagesCount;
    var actual = calculatePagesCount(pageSize, entry.itemsCount);
    
    var print = (expected === actual ? console.log : console.error);
  	print(expected + ' === ' + actual);
}
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join