Guest User

Untitled

a guest
Mar 19th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. const User = function(name) {
  2. this.name = name;
  3. this.chatroom = null;
  4. }
  5.  
  6. User.prototype = {
  7. send: function(message, to) {
  8. this.chatroom.send(message, this, to);
  9. },
  10. recieve: function(message, from) {
  11. console.log(`${from.name} to ${this.name}: ${message}`);
  12. }
  13. }
  14.  
  15. const Chatroom = function() {
  16. let users = {}; // list of users
  17.  
  18. return {
  19. register: function(user) {
  20. users[user.name] = user;
  21. user.chatroom = this;
  22. },
  23. send: function(message, from, to) {
  24. if(to) {
  25. // Single user message
  26. to.recieve(message, from);
  27. } else {
  28. // Mass message
  29. for(key in users) {
  30. if(users[key] !== from) {
  31. users[key].recieve(message, from);
  32. }
  33. }
  34. }
  35. }
  36. }
  37. }
  38.  
  39. const brad = new User('Brad');
  40. const jeff = new User('Jeff');
  41. const sara = new User('Sara');
  42.  
  43. const chatroom = new Chatroom();
  44.  
  45. chatroom.register(brad);
  46. chatroom.register(jeff);
  47. chatroom.register(sara);
  48.  
  49. brad.send('Hello Jeff', jeff);
  50. sara.send('Hello Brad, you are the best dev ever!', brad);
  51. jeff.send('Hello Everyone!!!!');
Add Comment
Please, Sign In to add comment