Skip to content

Instantly share code, notes, and snippets.

@jremi
Last active November 15, 2020 18:51
Show Gist options
  • Save jremi/0fcd71cc32f3497b91364dc2cd2d731b to your computer and use it in GitHub Desktop.
Save jremi/0fcd71cc32f3497b91364dc2cd2d731b to your computer and use it in GitHub Desktop.
Simple es6 javascript chatroom fiddle
class ChatRoom {
constructor(roomName) {
if (!roomName)
throw new Error(
"ChatRoom name must be provided to create new chat room instance!"
);
this.roomName = roomName;
this.roomMembers = [];
}
join(member) {
if (!member) {
throw new Error(
"To join a chatroom you must provide a member object instance!"
);
}
if (!this.roomMembers.includes(member.username)) {
this.roomMembers.push(member.username);
console.log(`${member.username} joined #${this.roomName}`);
}
return this;
}
leave(member) {
if (!member) {
throw new Error(
"To leave a chatroom you must provide a member object instance!"
);
}
if (!this.roomMembers.includes(member.username)) {
throw new Error(`This member was not found in #${this.roomName}!`);
}
this.roomMembers = this.roomMembers.filter(
(username) => username !== member.username
);
console.log(`${member.username} has left #${this.roomName}`);
}
send(toUsername, fromUsername, message) {
if (!toUsername)
throw new Error(
"To direct message you must provide the room member username to send message!"
);
if (!fromUsername)
throw new Error(
"To direct message you must provide the room member username sending message!"
);
if (!message)
throw new Error("To message you must provide a message to send!");
console.log(`\nFrom: ${fromUsername}\nTo: ${toUsername} \n> ${message}\n`);
}
get currentRoomMembers() {
return this.roomMembers;
}
}
class Member {
constructor(options) {
if (!options.username)
throw new Error("Options object must contain username property!");
this.username = options.username;
this.chatRoom = null;
}
joinChatRoom(chatRoomInstance) {
this.chatRoom = chatRoomInstance.join(this);
}
leaveChatRoom() {
this.chatRoom.leave(this);
}
send(toUsername, message) {
if (!this.chatRoom)
throw new Error("You must first join a chatroom to send message!");
this.chatRoom.send(toUsername, this.username, message);
}
}
const GeneralChat = new ChatRoom("General");
const John = new Member({
username: "John",
});
const Jane = new Member({
username: "Jane",
});
John.joinChatRoom(GeneralChat);
Jane.joinChatRoom(GeneralChat);
John.send("Jane", "How is the coffee?");
Jane.send("John", "Very good flavor!");
// console.log(GeneralChat.currentRoomMembers);
John.leaveChatRoom();
Jane.leaveChatRoom();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment