Skip to content

Instantly share code, notes, and snippets.

@jagomf
Last active February 6, 2020 10:42
Show Gist options
  • Save jagomf/cd45b325c9cdc61301fe06a3febafa95 to your computer and use it in GitHub Desktop.
Save jagomf/cd45b325c9cdc61301fe06a3febafa95 to your computer and use it in GitHub Desktop.
Generate a simple calendar which is an array of arrays
/**
* Generates a simple Calendar formatted as an array of arrays
* @param year Year for which calendar month is generated
* @param month Calendar month to be generated
* @param startWeekMonday Optional offset -- defaults to false (week starts on Sunday)
* @returns Main array (month) of arrays (weeks) of days
* @see Based on algorithm by github:lukeed/calendarize
*/
private generateMonthCalendar(year: number, month: number, startWeekMonday = false) {
const res: number[][] = [];
const weekOffset = startWeekMonday ? 1 : 0;
let dayOfWeek = new Date(year, month, 1 - weekOffset).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
let day = 0;
while (day < daysInMonth) {
const week = Array(7);
for (let weekdayIterator = 0; weekdayIterator < 7;) {
while (weekdayIterator < dayOfWeek) {
week[weekdayIterator++] = 0;
}
week[weekdayIterator++] = ++day > daysInMonth ? 0 : day;
dayOfWeek = 0;
}
res.push(week);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment