create clendar class with constructor in pure js in javascript in javascript

Here's an example of how to create a Calendar class in pure JavaScript with a constructor:

class Calendar {
  constructor(year, month) {
    this.year = year;
    this.month = month;
    this.daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  }

  getDaysInMonth() {
    return new Date(this.year, this.month, 0).getDate();
  }

  getFirstDayOfWeek() {
    return new Date(this.year, this.month - 1, 1).getDay();
  }

  getMonthName() {
    return new Date(this.year, this.month - 1, 1).toLocaleString('default', { month: 'long' });
  }

  getCalendarTable() {
    const daysInMonth = this.getDaysInMonth();
    const firstDayOfWeek = this.getFirstDayOfWeek();
    const table = [];

    let day = 1;
    for (let i = 0; i < 6; i++) {
      const row = [];
      for (let j = 0; j < 7; j++) {
        if (i === 0 && j < firstDayOfWeek) {
          row.push('');
        } else if (day > daysInMonth) {
          row.push('');
        } else {
          row.push(day);
          day++;
        }
      }
      table.push(row);
      if (day > daysInMonth) break;
    }

    return table;
  }

  render() {
    const monthName = this.getMonthName();
    const daysOfWeek = this.daysOfWeek;
    const calendarTable = this.getCalendarTable();

    let html = `<table><caption>${monthName}</caption>`;
    html += `<tr>${daysOfWeek.map(day => `<th>${day}</th>`).join('')}</tr>`;
    calendarTable.forEach(row => {
      html += '<tr>';
      row.forEach(day => {
        html += `<td>${day}</td>`;
      });
      html += '</tr>';
    });
    html += '</table>';

    return html;
  }
}

const calendar = new Calendar(2022, 1);
console.log(calendar.render());
1579 chars
67 lines

In this implementation of Calendar, the constructor takes in a year and month parameter and also initializes an array of days of the week.

The getDaysInMonth() method calculates the number of days in the calendar's month using the Date object. Similarly, the getFirstDayOfWeek() method uses the Date object to determine the first day of the week in the calendar's month.

The getMonthName() method returns the name of the calendar's month in a human-readable format.

The getCalendarTable() method generates a 2D array representing the calendar's table, with empty cells corresponding to days in the previous or following months.

Finally, the render() method puts everything together and generates an HTML table representing the calendar, with the month name, days of the week, and calendar table.

gistlibby LogSnag