Skip to content

Instantly share code, notes, and snippets.

@theuves
Last active September 30, 2019 03:08
Show Gist options
  • Save theuves/c69aa17f43357e46da603d38ddaa3773 to your computer and use it in GitHub Desktop.
Save theuves/c69aa17f43357e46da603d38ddaa3773 to your computer and use it in GitHub Desktop.
Array calendar.
function otherMonthDayString(string) {
return `\x1b[36m${string}\x1b[0m`
}
function todayString(string) {
return `\x1b[42m${string}\x1b[0m`
}
function getCalendarArray(year, month) {
const CALENDAR_ROW = 5
const CALENDAR_COL = 7
const DAY_TIME = 86400000
const firstMonthDay = new Date(`${year} ${month} 1`)
const initialDay = firstMonthDay.getTime() - DAY_TIME * firstMonthDay.getDay()
const calendarDays = []
const calendar = []
for (let i = 0; i < CALENDAR_ROW * CALENDAR_COL; i++) {
calendarDays.push((new Date(initialDay + DAY_TIME * i).getDate()))
}
for (let i = 0; i < CALENDAR_ROW * CALENDAR_COL; i = i + CALENDAR_COL) {
calendar.push(calendarDays.slice(i, i + CALENDAR_COL))
}
return calendar
}
function printCalendar(calendar, year, month) {
const SPACE = ' '
const date = new Date()
const currentDay = date.getDate()
const currentYear = date.getFullYear()
const currentMonth = date.getMonth() + 1
const isInThisYearnAndMonth = currentYear === year && currentMonth === month
const calendarStrings = calendar.map((rowDays, rowIndex) => {
rowDays = rowDays.map(day => {
const stringValue = day.toString().padStart(2, SPACE)
if (isInThisYearnAndMonth && parseInt(stringValue) === currentDay) {
return todayString(stringValue)
}
return rowIndex === 0 && day > 7 || rowIndex === 4 && day < 25
? otherMonthDayString(stringValue)
: stringValue
})
return rowDays.join(SPACE)
})
console.log(calendarStrings.join('\n'))
}
function main() {
const date = new Date()
const year = process.argv[2] ? parseInt(process.argv[2]) : date.getFullYear()
const month = process.argv[3] ? parseInt(process.argv[3]) : date.getMonth() + 1
const calendarArray = getCalendarArray(year, month)
printCalendar(calendarArray, year, month)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment