Krok 4: testy modelu w konsoli
Kalendarz: logika oddzielona od widoku - Kalendarz w JavaScript krok po kroku (JavaScript)
Model bez strony łatwo sprawdzić: funkcja `check(opis, wynik, oczekiwane)` wypisuje `OK` albo `BŁĄD`. Testy pilnują, że listopad 2026 ma 6 tygodni, luty 2027 cztery, a dni trafiają do właściwych kolumn. Po każdej zmianie modelu wystarczy uruchomić program i przejrzeć listę.
const sameDay = (a, b) =>
a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
// model: miesiąc jako tablica tygodni, dzień = obiekt z informacjami, puste pole = null
function monthWeeks(year, month, today) {
const firstDay = (new Date(year, month - 1, 1).getDay() + 6) % 7;
const days = new Date(year, month, 0).getDate();
const cells = Array(firstDay).fill(null);
for (let d = 1; d <= days; d++) {
cells.push({
day: d,
weekend: (firstDay + d - 1) % 7 >= 5,
today: sameDay(new Date(year, month - 1, d), today),
});
}
while (cells.length % 7 !== 0) cells.push(null);
const weeks = [];
for (let i = 0; i < cells.length; i += 7) weeks.push(cells.slice(i, i + 7));
return weeks;
}
function check(label, actual, expected) {
console.log((actual === expected ? 'OK ' : 'BŁĄD ') + label);
}
const today = new Date(2026, 10, 13);
const november = monthWeeks(2026, 11, today);
check('listopad 2026 ma 6 tygodni', november.length, 6);
check('luty 2027 ma 4 tygodnie', monthWeeks(2027, 2, today).length, 4);
check('1 listopada to niedziela', november[0][6].day, 1);
check('7 listopada to weekend', november[1][5].weekend, true);
check('13 listopada to piątek i dzisiaj', november[2][4].day === 13 && november[2][4].today, true);
check('ostatnie pole listopada jest puste', november[5][6], null);Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu Kalendarz w JavaScript krok po kroku·Zaloguj się, aby zapisać postęp na koncie.