0

Classes emitter and receiver are supposed to send and receive messages. Why is the receiver not receiving any messages and how should I fix it?

const solution = (messages) => {
    class Emitter {
        constructor(messages = []) {
            this.messages = messages;
            this.event = () => {};
        }
        setEvent(fn) {
            this.event = fn;
        }
        trigger() {
            this.messages.forEach(message => this.event(message));
        }
    }
    
    class Receiver {
        constructor() {
            this.messages = [];
        }
        ping(message) {
            this.messages.push(message);
        }
    }
    
    let emi = new Emitter(messages);
    let rec = new Receiver();
    emi.setEvent(rec.ping);
    emi.trigger();
    console.log(rec.messages); // []
    console.log(emi.messages) // ['hi','hola','hi','hola']
}
solution(['hi','hola']);
Akshay Kumar
  • 61
  • 1
  • 1
  • 7
  • 1
    Please use a title that briefly explains the problem. And in my opinion, SO is not the place for help with your job interview. The point is "can he fix this" not "Can he ask someone to fix this". – Gert B. Jan 21 '22 at 14:21
  • 1
    Receiver can accept messages if your pass its method 'ping' bounded to the instance of receiver class, like so: `emi.setEvent(rec.ping.bind(rec));` – Konstantin Samarin Jan 21 '22 at 14:24
  • 1
    Also see [how-does-the-this-keyword-work](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – ASDFGerte Jan 21 '22 at 14:24
  • @GertB. The job interview is over. I couldn't solve it. That's why I'm asking here – Akshay Kumar Jan 21 '22 at 14:25
  • `ping(message) { console.log(this); ` – epascarello Jan 21 '22 at 14:26
  • 1
    The first hint would be that `emi.messages` contains four elements (`['hi','hola','hi','hola']`) at the end, although it started with two (`solution(['hi','hola'])`) – Andreas Jan 21 '22 at 14:29
  • 1
    [When should I use arrow functions in ECMAScript 6?](https://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6), [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable) – Andreas Jan 21 '22 at 14:41

0 Answers0