Scriptdrill

Level 5: Async and functions Exercise 73 of 76 Free

Event emitter

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Return an emitter object with three methods. `on(event, handler)` registers a handler for the event name and returns a function that removes that registration. `off(event, handler)` removes one registration of that handler (nothing happens when it is not registered). `emit(event, ...args)` calls every handler registered for the event, in registration order, with the arguments, and returns the number of handlers called (0 when there are none). The same handler registered twice runs twice. Removing a handler while an emit is running does not change which handlers that emit calls. Every emitter has its own handlers.

What this exercise teaches

Arrays keep duplicates and order, which a Set would collapse. Iterating a copy keeps an emit stable when a handler removes itself, because splicing the live array during the loop shifts the next handler into the slot you just visited.

A hint if you get stuck

Keep a `Map` from event name to an array of handlers inside `createEmitter`. In `emit`, loop over a copy of the array (`[...handlers]`) so removals during the loop do not skip anyone. `on` can return `() => off(event, handler)`.

Try it now, free, no account needed

Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Async and functions