Skip to content

Instantly share code, notes, and snippets.

@dra1n
Created May 7, 2024 07:48
Show Gist options
  • Save dra1n/87b7c6ca21c44d08e25c4be84dd39ed4 to your computer and use it in GitHub Desktop.
Save dra1n/87b7c6ca21c44d08e25c4be84dd39ed4 to your computer and use it in GitHub Desktop.
class ChatRoom {
constructor(users = []) {
this.users = users;
}
addUser(user) {
this.users.push(user);
}
sendMessage(user, message) {
const sender = user.getName();
this.users.filter(u => u !== user).forEach(u => u.receive(sender, message));
}
}
class User {
constructor(name, chatroom) {
this.name = name;
this.chatroom = chatroom;
}
getName() {
return this.name;
}
send(message) {
this.chatroom.sendMessage(this, message);
}
receive(sender, message) {
console.log(`${new Date().toLocaleString()} [${sender}]: ${message}`);
}
}
const chatroom = new ChatRoom();
const user1 = new User("John Doe", chatroom);
const user2 = new User("Jane Doe", chatroom);
chatroom.addUser(user1);
chatroom.addUser(user2);
user1.send("Hi there!");
user2.send("Hey!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment