Simulate how a browser dispatches a bubbling event. The page is parentOf, mapping each id to its parent id (the root maps to null). listeners lists event listeners in the order they were added; each is { node, capture, name }.
The event travels the path from the root down to targetId (capture phase), then back up from the target to the root (bubble phase). On the way down, each element runs its listeners with capture: true; on the way up, each element runs its listeners with capture: false. The target is visited by both: its capture listeners run first, then its others. Within one element and phase, listeners run in the order they were added.
Write dispatchOrder(parentOf, targetId, listeners) that returns the names of the listeners in the order they run.
Input: parentOf = {"root":null,"form":"root","field":"form","input":"field","submit":"form","aside":"root"}, targetId = "submit", listeners = [{"node":"root","capture":true,"name":"log"},{"node":"submit","capture":false,"name":"click"},{"node":"form","capture":false,"name":"validate"},{"node":"submit","capture":true,"name":"focusRing"}] Output: ["log","focusRing","click","validate"]
Down: root runs log, then the target runs its capture listener focusRing. Up: the target runs click, then form runs validate.
Input: parentOf = {"root":null,"form":"root","field":"form","input":"field","submit":"form","aside":"root"}, targetId = "input", listeners = [{"node":"aside","capture":false,"name":"sidebar"},{"node":"field","capture":false,"name":"field"},{"node":"root","capture":false,"name":"root"}] Output: ["field","root"]
aside isn't on the path from input to the root, so it never runs.
parentOf has 1 to 10^3 entries; 0 <= listeners.length <= 10^3.node is a key of parentOf.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).
I'm here to help with #707 Which Listeners Run, and When. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.