Languages
[Edit]
EN

JavaScript - calculate number of pages from size of page and total number of items

7 points
Created by:
Greg
7850

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

  • maximal size of the page,
  • a total number of items.

Simple example:

// ONLINE-RUNNER:browser;

const 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:

const pageSize = 10;
const totalCount = 21;
const pagesCount = calculatePagesCount(pageSize, totalCount);

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

The above logic result explanation:

  • the total number of items is 21 (totalCount variable),
  • the maximal size of the page is 10 items (pageSize variable),

So:

  • page 1 should have 10 items
  • page 2 should have 10 items
  • page 3 should have  1 item

so we have 3 pages.

 

Testing

In this section we present simple test for different calculatePagesCount() usage cases.

// ONLINE-RUNNER:browser;

const 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:

const pageSize = 10;

const testingData = [
//  { input             expected        }
    { totalCount:    0, pagesCount:   1 }, // 1 empty page
    { totalCount:    1, pagesCount:   1 },
    { totalCount:   10, pagesCount:   1 },
    { totalCount:   11, pagesCount:   2 },
    { totalCount:   99, pagesCount:  10 },
    { totalCount:  100, pagesCount:  10 },
    { totalCount:  101, pagesCount:  11 }
];

console.log('Pages count:');
console.log('[expected]\t[actual]');

for (const entry of testingData) {
    const pagesCount = calculatePagesCount(pageSize, entry.totalCount);
  	if (entry.pagesCount !== pagesCount) {
    	throw new Error('Pages count calculator error.');
    }
    console.log(entry.pagesCount + '\t\t' + pagesCount); // expected vs actual
}

 

See also

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

Alternative titles

  1. JavaScript - the simplest formula to calculate page count
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join