Created
September 10, 2017 20:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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