EN
JavaScript - calculate number of pages from size of page and total number of items
7 points
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:
xxxxxxxxxx
1
const calculatePagesCount = (pageSize, totalCount) => {
2
// we suppose that if we have 0 items we want 1 empty page
3
return totalCount < pageSize ? 1 : Math.ceil(totalCount / pageSize);
4
};
5
6
7
// Example usage:
8
9
const pageSize = 10;
10
const totalCount = 21;
11
const pagesCount = calculatePagesCount(pageSize, totalCount);
12
13
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 have10
items- page
2
should have10
items- page
3
should have1
itemso we have
3
pages.
In this section we present simple test for different calculatePagesCount()
usage cases.
xxxxxxxxxx
1
const calculatePagesCount = (pageSize, totalCount) => {
2
// we suppose that if we have 0 items we want 1 empty page
3
return totalCount < pageSize ? 1 : Math.ceil(totalCount / pageSize);
4
};
5
6
7
// Exmaple tests:
8
9
const pageSize = 10;
10
11
const testingData = [
12
// { input expected }
13
{ totalCount: 0, pagesCount: 1 }, // 1 empty page
14
{ totalCount: 1, pagesCount: 1 },
15
{ totalCount: 10, pagesCount: 1 },
16
{ totalCount: 11, pagesCount: 2 },
17
{ totalCount: 99, pagesCount: 10 },
18
{ totalCount: 100, pagesCount: 10 },
19
{ totalCount: 101, pagesCount: 11 }
20
];
21
22
console.log('Pages count:');
23
console.log('[expected]\t[actual]');
24
25
for (const entry of testingData) {
26
const pagesCount = calculatePagesCount(pageSize, entry.totalCount);
27
if (entry.pagesCount !== pagesCount) {
28
throw new Error('Pages count calculator error.');
29
}
30
console.log(entry.pagesCount + '\t\t' + pagesCount); // expected vs actual
31
}