Skip to content

Instantly share code, notes, and snippets.

@bushidocodes
Created September 10, 2017 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bushidocodes/fd955c29aad283e2bf93044cf3b819f8 to your computer and use it in GitHub Desktop.
Save bushidocodes/fd955c29aad283e2bf93044cf3b819f8 to your computer and use it in GitHub Desktop.
Use Recursive Iterators to use a for...of on a tree data structure
// goal: Use generators to iterate through a tree
// Create a class that has children and an iterator that recurses over the children
class Node {
constructor(value, children) {
this.value = value;
this.children = children;
}
*[Symbol.iterator]() {
yield this.value;
for (let child of this.children) {
yield* child;
}
}
}
// Create an example tree
const children = [
new Node('good comment', []),
new Node('bad comment', []),
new Node('meh', []),
];
const tree = new Node('Great post dude!', children);
// Iterate over the node values of the tree
for (let node of tree) {
console.log(node);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment