Learning on Web Dev Open is free for all.

Interview Prep · CodeBuild an event emitter
← Code

Build an event emitter

Easy20 minFree, no account

Twelve lines that work, and one edge case that almost everybody ships broken.


The question

Implement on, off, once and emit.

Then handle the case where a listener removes another listener, or itself, during emit.

const bus = new Emitter();
const un = bus.on("tick", n => console.log(n));
bus.emit("tick", 1);   // logs 1
un();                  // on() returns an unsubscribe
bus.once("tick", f);   // runs at most once
20:00Commit to an answer before you open the solution. Reading it first teaches you to recognise good answers, which is not the skill being tested.

Stuck?

0 of 3 hints taken

The worked solution

written by a person · not a grade

Score yourself

0 of 4 marked
  • Correct on/off/once/emit30
  • Handled removal during emit and explained why30
  • off removes a once-wrapped handler by its original reference20
  • Had a position on throwing listeners and stated complexity20

We run no AI here and nothing on this page grades you. The score is yours, and the useful number is the one you get on the same problem a month from now, cold.

kept in this browser only