PL
JavaScript - jak obliczyć liczbę stron, gdy znamy rozmiar strony i całkowitą liczbę elementów?
0 points
W tym artykule przyjrzymy się, jak w JavaScript obliczyć liczbę stron, gdy znamy:
- rozmiar strony,
- łączną liczbę pozycji.
Prosty przykład:
xxxxxxxxxx
1
function calculatePagesCount(pageSize, totalCount) {
2
// zakładamy, że jeśli mamy 0 elementów, chcemy mieć 1 pustą stronę
3
return totalCount < pageSize ? 1 : Math.ceil(totalCount / pageSize);
4
}
5
6
// Przykład użycia:
7
8
var pageSize = 10;
9
var itemsCount = 21;
10
var pagesCount = calculatePagesCount(pageSize, itemsCount);
11
12
console.log('liczba stron = ' + pagesCount); // 3
13
14
// Wyjaśnienie wyniku:
15
// strona 1 -> 10 pozycji
16
// strona 2 -> 10 pozycji
17
// strona 3 -> 1 pozycja
Przykładowe testy:
xxxxxxxxxx
1
function calculatePagesCount(pageSize, totalCount) {
2
// zakładamy, że jeśli mamy 0 elementów, chcemy mieć 1 pustą stronę
3
return totalCount < pageSize ? 1 : Math.ceil(totalCount / pageSize);
4
}
5
6
// Przykładowe testy:
7
8
var pageSize = 10;
9
var testingData = [
10
{ itemsCount: 0, expectedPagesCount: 1 }, // 1 pusta strona
11
{ itemsCount: 1, expectedPagesCount: 1 },
12
{ itemsCount: 10, expectedPagesCount: 1 },
13
{ itemsCount: 11, expectedPagesCount: 2 },
14
{ itemsCount: 99, expectedPagesCount: 10 },
15
{ itemsCount: 100, expectedPagesCount: 10 },
16
{ itemsCount: 101, expectedPagesCount: 11 }
17
];
18
19
for (var i = 0; i < testingData.length; ++i) {
20
var entry = testingData[i];
21
22
var expected = entry.expectedPagesCount;
23
var actual = calculatePagesCount(pageSize, entry.itemsCount);
24
25
var print = (expected === actual ? console.log : console.error);
26
print(expected + ' === ' + actual);
27
}