Skip to content

Instantly share code, notes, and snippets.

@samcorcos
Last active April 4, 2020 17:49
Show Gist options
  • Save samcorcos/384e3be6d171818bf4060f376da38737 to your computer and use it in GitHub Desktop.
Save samcorcos/384e3be6d171818bf4060f376da38737 to your computer and use it in GitHub Desktop.
const generateCalendar = (today: Date) => {
const daysInMonth = getDaysInMonth(today)
const firstDay = new Date(today.getFullYear(), today.getMonth()).getDay()
// in order to calculate how many calendar weeks there are (starting on Sunday), we can take
// days in the month and add first day + 1 to include the first week offset. returns an array
// that looks something like this:
// [undefined, undefined, undefined, 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]
const daysWithOffset = new Array(daysInMonth + firstDay).fill(undefined).map((v, i) => {
if (i < firstDay) {
return undefined
}
// otherwise, return the index minus the firstDay value to remove the offset
return i - firstDay + 1
})
// the number of weeks to render in the component
const weeks = Math.ceil(daysWithOffset.length / 7)
// since we know how many weeks there are, we can slice it `n` weeks number of times
const month = new Array(weeks).fill(undefined).reduce((acc, _w, i) => {
// split the weeks into chunks of 7 days
const week = daysWithOffset.slice(i * 7, i * 7 + 7)
// if it's the last week, make sure it's the full length (7)
if (i === weeks - 1) {
// calculate how many undefined spaces we need at the end of the last week
const endOffset = new Array(7 - week.length).fill(undefined)
return [...acc, [...week, ...endOffset]]
}
return [...acc, week]
}, [])
// at this point we have something like:
// [[undefined, undefined, undefined, 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, undefined, undefined]]
// which we can use to generate a calendar component for a given month
return month
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment