Created
May 7, 2024 07:48
-
-
Save dra1n/87b7c6ca21c44d08e25c4be84dd39ed4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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