Prints a calendar

Prints a simple calendar in the browser console.

Take a look at the output and give it a shot using your own approach!

p.s. I appreciate your feedback in advance.

class Calendar {

// Returns the total number of days in this month.
  daysInMonth() {
    const date = new Date();
    const totalDays = new Date(
      date.getFullYear(),
      date.getMonth() + 1,
      0
    ).getDate();

    return totalDays;
  }

  //Generates the calendar table
  generateCal() {
    const maxDays = this.daysInMonth();
    const month = Array(maxDays);
    let week = [];

    for (let day of month.keys()) {
      // When we have counted to the end of the current week, print, empty the arrray, then continue counting with subsequent weeks.
      if (day && day % 7 == 0) {
        flush();
      }
      week.push(day + 1);
    }

    // Print the final week as well.
    flush();

    function flush() {
      week = week.map((v) => (v < 10 ? "0" + v : v));

      console.log(week.join(" | "));
      week.length = 0;
    }
  }
}

let calendar = new Calendar();


// Prints a simple calendar to the console.
calendar.generateCal();

A few possible enhancements:

  • Add the Month/Year above the calendar.
  • Add the days of the week, or at least the days for the leftmost and rightmost columns.
  • Start the month on the correct day of the week.
  • Add in the ability to specify which month/year to generate. For example, you could pass the month and year to generateCal().

Thank you for your feedback! I appreciate it.

Accordingly, I have updated the code to include what you suggested.
The showCal() function below accepts 0 or 2 arguments.

If no arguments are given, then it shows a calendar for the current month in the console.

If it is provided with arguments in the form showCal(year, month), then the printed calendar will show the given month of the given year in the console.

class Calendar {
  constructor(yearX, monthY) {
    this.year = yearX;
    this.month = monthY;
  }

  _daysInMonth;
  _weekStartDay;
  _year;
  _month;

  // Getters and setters to validate input from user and return input if needed.
  get year() {
    return this._year;
  }

  get month() {
    return this._month;
  }

  set year(value) {
    if (Number.isInteger(value) && value > 1970 && value < 5000) {
      this._year = Math.trunc(Math.abs(value));
    } else {
      console.warn(`Enter a valid year.`);
      console.info(`Year range: 1970 - 5000`);
    }
  }

  set month(value) {
    if (Number.isInteger(value) && value >= 1 && value <= 12) {
      this._month = Math.trunc(Math.abs(value));
      this._month--;
    } else {
      console.warn(`Enter a valid month.`);
      console.info(`Month range: 1 - 12`);
    }
  }

  // Grabs the amount of days in the spicified month, and the day of the week that the month starts.
  generateCal() {
    this._daysInMonth = new Date(this._year, this._month + 1, 0).getDate();
    this._weekStartDay = new Date(this._year, this._month).getDay();
  }

  printCal() {
    // Initialize object properties
    this.generateCal();

    const WEEKDAYS = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"];
    const MONTHS = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December",
    ];

    // Print year and month
    console.log(`\n\t${this._year}\n\t${MONTHS[this._month]}\n`);

    // Print weekdays
    console.log(WEEKDAYS.join(" | "));

    // Initialize the buffer
    let buffer = Array(7);
    buffer.fill("  ");

    // Print calendar days
    for (
      let day = 1, pos = this._weekStartDay;
      day <= this._daysInMonth;
      day++, pos++
    ) {
      if (pos && pos > 6) {
        flush();
        pos = 0;
      }

      buffer[pos] = day;
    }

    // print the last week
    flush();

    function flush() {
      // Pad a `0' to the left of single digits.
      buffer = buffer.map((v) =>
        v < 10 && typeof v == "number" ? "0" + v : v
      );
      console.log(buffer.join(" | "));
      buffer.fill("  ");
    }
  }
}

// Initialize calendar object
const currentDate = new Date();
const calendar = new Calendar(
  currentDate.getFullYear(),
  currentDate.getMonth() + 1
);

// Create a wrapper function to easily print calendar
function showCal(year, month) {
  if (arguments.length == 2) {
    calendar.year = year;
    calendar.month = month;
  }
  calendar.printCal();
}

// Print the calendar with optional args.
showCal(2013, 8);

I am always open to more suggestions and corrections :+1:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.