Replay event delegation up an ancestor chain
One listener on a container beats a hundred listeners on rows, which is why delegation is everywhere. What it costs you is intuition about ordering: which handler runs first when two match, and what stopPropagation actually stops. This models it exactly.
You are given chain, an array of plain nodes ordered from the event target first to the outermost ancestor last — the same order as event.composedPath(). Each node is { tag, attrs }, and attrs may be missing. You are also given handlers, an array of { name, match, stopPropagation } in registration order, where stopPropagation is optional.
A match is a plain object that may contain tag, id and class. A node matches when every field present in match matches: tag compared case-insensitively against node.tag; id compared exactly against attrs.id; class required as a whole whitespace-separated token of attrs.class. An empty match object matches every node.
Implement dispatch(chain, handlers) returning an array of handler name values in firing order. Walk chain from index 0 outwards, and at each node fire every matching handler in registration order, appending its name. If any handler that fired at the current node has stopPropagation: true, all remaining matching handlers on that same node still fire, and then the walk stops without visiting any further ancestors. Return [] when nothing matches.
What it has to do
- Return handler names in firing order: node by node from the target outwards, and by registration order within a node.
- Match on
tagcase-insensitively,idexactly, andclassas a whole whitespace-separated token. - Treat an empty
matchobject as matching every node. - Let every matching handler on the current node fire even when one of them sets
stopPropagation, then stop before the next ancestor. - Return
[]when no handler matches, and tolerate nodes with noattrs.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.