How would you implement a custom Symbol.iterator for a tree data structure to enable depth-first traversal with for...of?
Short answer
Implement [Symbol.iterator]() as a generator method (using function*), recursively yielding each node's value and delegating to child nodes with yield* — this lets a complex, non-linear structure be consumed with simple, idiomatic for...of syntax.
Advertisement
AModel answer
Implement [Symbol.iterator]() as a generator method (using function*), recursively yielding each node's value and delegating to child nodes with yield* — this lets a complex, non-linear structure be consumed with simple, idiomatic for...of syntax.
class TreeNode {
constructor(value, children = []) {
this.value = value;
this.children = children;
}
*[Symbol.iterator]() {
yield this.value;
for (const child of this.children) {
yield* child; // delegates to each child's iterator
}
}
}Real-world example
Traversing a nested comment thread or file-system-like tree structure with a plain for...of loop.
Likely follow-ups
- How would you modify this for breadth-first instead of depth-first traversal?
Related topics