Event Emitter

Medium~20 min

Implement an EventEmitter class that supports subscribing to events and emitting them.

Since test cases cannot pass actual callback functions, we use integer IDs to represent callbacks.

The EventEmitter class should support the following operations:

  • EventEmitter() — Initialize the event emitter.
  • on(event, callbackId) — Register the integer callbackId for the given event name (a string). Multiple IDs can be registered for the same event, and the same ID can be registered multiple times.
  • emit(event) — Trigger the given event. Return an array of all registered callback IDs for that event, in the order they were registered. If the event has no subscribers, return an empty array.
  • off(event, callbackId) — Remove the first occurrence of callbackId from the given event. If the ID is not registered for that event, do nothing.

Examples

Example 1
Input: ["EventEmitter","on","on","emit","off","emit"] [[],["click",1],["click",2],["click"],["click",1],["click"]]
Output: [null,null,null,[1,2],null,[2]]
Explanation: EventEmitter emitter = new EventEmitter(); emitter.on("click", 1); // register id 1 for "click" emitter.on("click", 2); // register id 2 for "click" emitter.emit("click"); // return [1, 2] emitter.off("click", 1); // remove id 1 from "click" emitter.emit("click"); // return [2]

Constraints

  • Event names are non-empty strings
  • 1 <= callbackId <= 1000
  • At most 1000 calls will be made to on, emit, and off
  • The same callbackId can be registered multiple times for the same event
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run