Skip to content

Instantly share code, notes, and snippets.

@mahdisoultana
Forked from getify/1-CalendarItem.js
Created July 16, 2022 12:11
Show Gist options
  • Save mahdisoultana/5564a2fb42df7b0ac2cb02255a46e63f to your computer and use it in GitHub Desktop.
Save mahdisoultana/5564a2fb42df7b0ac2cb02255a46e63f to your computer and use it in GitHub Desktop.
a non-trivial example of newer JS class features
class CalendarItem {
static #UNSET = Symbol("unset")
static #isUnset(v) {
return v === this.#UNSET;
}
static isSameItem(item1,item2) {
if (#ID in item1 && #ID in item2) {
return item1.#ID === item2.#ID;
}
else {
return false;
}
}
#ID = CalendarItem.#UNSET
#setID(id) {
if (CalendarItem.#isUnset(this.#ID)) {
this.#ID = id;
}
else {
throw new Error("ID is already set");
}
}
description = null
startDateTime = null
constructor() {
if (new.target !== CalendarItem) {
let id = Math.round(Math.random() * 1e9);
this.#setID(id);
}
else {
throw new Error("Don't instantiate 'CalendarItem' directly.");
}
}
getID() {
if (!CalendarItem.#isUnset(this.#ID)) {
return this.#ID;
}
else {
throw new Error("ID is unset");
}
}
getDateTimeStr() {
if (this.startDateTime instanceof Date) {
return this.startDateTime.toUTCString();
}
}
summary() {
console.log(`(${
this.getID()
}) ${
this.description
} at ${
this.getDateTimeStr()
}`);
}
}
class Reminder extends CalendarItem {
#complete = false
constructor(description,startDateTime) {
super();
this.description = description;
this.startDateTime = startDateTime;
}
isComplete() {
return !!this.#complete;
}
markComplete() {
this.#complete = true;
}
summary() {
if (this.isComplete()) {
console.log(`(${this.getID()}) Complete.`);
}
else {
super.summary();
}
}
}
class Meeting extends CalendarItem {
endDateTime = null
#getEndDateTimeStr() {
if (this.endDateTime instanceof Date) {
return this.endDateTime.toUTCString();
}
}
constructor(description,startDateTime,endDateTime) {
super();
this.description = description;
this.startDateTime = startDateTime;
this.endDateTime = endDateTime;
}
getDateTimeStr() {
return `${
super.getDateTimeStr()
} - ${
this.#getEndDateTimeStr()
}`;
}
}
var callMyParents = new Reminder(
"Call my parents to say hi",
new Date("July 7, 2022 11:00:00 UTC")
);
callMyParents.summary();
// (586380912) Call my parents to say hi at
// Thu, 07 Jul 2022 11:00:00 GMT
callMyParents.markComplete();
callMyParents.summary();
// (586380912) Complete.
var interview = new Meeting(
"Job Interview: ABC Tech",
new Date("June 23, 2022 08:30:00 UTC"),
new Date("June 23, 2022 09:15:00 UTC")
);
interview.summary();
// (994337604) Job Interview: ABC Tech at Thu,
// 23 Jun 2022 08:30:00 GMT - Thu, 23 Jun 2022
// 09:15:00 GMT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment