/** * library to play around with date, year, month. * */ import {weekDayOfDate, countDaysOfMonth} from "./chronos.js"; /** * represents a monthly calendar-sheet, contains required data to generate a view of a Calendar-month. * */ export const Calendar = { /** * Define the first day of a week, which is shown in a Calendar View * Days of week are coded as follows: * 0 → Sunday, 1 → Monday, 2 → Tuesday, ... , 6 → Saturday * we set firstDayOfWeek by default to 1. * It is Monday, as convenient in Germany. * */ _firstDayOfWeek: 1, get firstDayOfWeek() { return this._firstDayOfWeek; }, set firstDayOfWeek(firstDayOfWeek) { this._firstDayOfWeek = firstDayOfWeek; }, /** * return an object with following structure: * * ```{ * month: 1, * year: 1970, * weekdays: [1, 2, 3, 4, 5, 6, 0], * weeks: [ * ["","","", 1, 2, 3, 4], * [5, 6, 7, 8, 9,10,11], * [12,13,14,15,16,17,18], * [19,20,21,22,23,24,25], * [26,27,28,29,30,31,""] * ] * }``` * * this structure is intended to be used to create a View of Calendar without * further calculation. * * @param {number} month * @param {number} year * * */ buildCalendar : function(month, year) { let cal = { month: month, year: year, weekDays: [], weeks:[] }; const DAYS_IN_WEEK = 7; for(let i = 0; i < DAYS_IN_WEEK; ++i) { let d = (i + Calendar._firstDayOfWeek) % DAYS_IN_WEEK; cal.weekDays.push(d); } // calculate how many days of last month get place in the first week // of this month const dayOfFirstDate = weekDayOfDate(1, month, year); const diff = (DAYS_IN_WEEK + (dayOfFirstDate - Calendar._firstDayOfWeek)) % DAYS_IN_WEEK; let countSpace = diff; let firstWeek = []; while(countSpace-- > 0) { firstWeek.push(""); } // append days of first week let d = 1; for (; d + diff <= 7; d++) { firstWeek.push(d); } // append the first week to result cal.weeks.push(firstWeek); // append the further weeks (2. 3. 4. maybe 5.) to result let daysOfMonth = countDaysOfMonth(month, year); let week = []; for(;d <= daysOfMonth; ++d) { week.push(d); if ( (d + diff) % 7 === 0 ) { cal.weeks.push(week); week = []; } } if (week.length > 0) { cal.weeks.push(week); } return cal; } }