Skip to the code
cf.
+50 XP

#709 Listeners with Stop Calls

hard

Extend the event dispatch simulation with stopping and non-bubbling events. The page is parentOf (each id to its parent id; the root maps to null). Each listener is { node, capture, name } and may also have stop: "propagation" or "immediate". Listeners are given in the order they were added.

Dispatch visits steps in this order: each element from the root down to the target with capture listeners, then each element from the target back up to the root with non-capture listeners. If bubbles is false, the way back up only visits the target itself (its non-capture listeners still run), not its ancestors.

When a listener with stop: "propagation" runs, the remaining listeners of the current step still run, but no later step does. This includes the target's non-capture step if the stop happened in its capture step. When a listener with stop: "immediate" runs, nothing else runs at all, not even the rest of the current step.

Write dispatch(parentOf, targetId, bubbles, listeners) that returns the names of the listeners that ran, in order.

Example 1

Input: parentOf = {"root":null,"form":"root","field":"form","input":"field","submit":"form","aside":"root"}, targetId = "input", bubbles = true, listeners = [{"node":"form","capture":true,"name":"formDown"},{"node":"input","capture":false,"name":"a","stop":"propagation"},{"node":"input","capture":false,"name":"b"},{"node":"field","capture":false,"name":"fieldUp"}]
Output: ["formDown","a","b"]

a stops propagation, but b is on the same element and step, so it still runs. field never hears the event.

Example 2

Input: parentOf = {"root":null,"form":"root","field":"form","input":"field","submit":"form","aside":"root"}, targetId = "input", bubbles = false, listeners = [{"node":"root","capture":true,"name":"rootDown"},{"node":"input","capture":false,"name":"self"},{"node":"form","capture":false,"name":"formUp"}]
Output: ["rootDown","self"]

The event doesn't bubble, so after the target nothing runs on the way up.

Constraints

  • parentOf has 1 to 10^3 entries; 0 <= listeners.length <= 10^3.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).