Created
March 25, 2018 06:00
-
-
Save C-Rodg/5f844b3da7f1a402b72786b966d40849 to your computer and use it in GitHub Desktop.
Depth-first searching of a tree using generators.
This file contains hidden or 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
class Tree { | |
constructor(value = null, children = []) { | |
this.value = value; | |
this.children = children; | |
} | |
*printValues() { | |
yield this.value; | |
for(let child of this.children) { | |
yield* child.printValues; | |
} | |
} | |
} | |
const tree = new Tree(1, [ | |
new Tree(2, [new Tree(4)]), | |
new Tree(3) | |
]); | |
const values = []; | |
for (let value of tree.printValues()) { | |
values.push(value); | |
} | |
// [1, 2, 4, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment