I am trying to implement a custom iterator in JavaScript that can traverse a DOM tree based on specific criteria provided by a callback function. The goal is to return an array of the nodes that match the criteria as the generator iterates through the tree structure.
root
/ \
P1 P2
| |
T1 T2
The idea is to use iter.next(isP)
or iter.next(isText)
to update the matcher and move to the next matching node in the tree.
type Matcher = (node: INode) => boolean
export function* nextNode(node: INode, matcher: Matcher = () => true, store: []): Generator<INode, any, Matcher> {
let reset: Matcher = matcher
store = store.concat(node)
if (reset(node)) {
reset = yield store
store = []
}
if (node.children) {
for (let childNode of node.children) {
yield *nextNode(childNode, matcher, store)
}
}
return
}
One issue I have encountered is that the reset
variable gets lost as the function call stack is popped. This causes problems when trying to switch the matcher in the middle of traversal, such as going from one text node to another. How can this be addressed?
const iter = nextNode(root, isT)
iter.next() <-- currently at T1
iter.next(isP) <-- expected to go to T2 instead of P2