Last active
July 10, 2018 03:21
-
-
Save misstonbon/83f8455b73646c01f553d073a8c94129 to your computer and use it in GitHub Desktop.
Iterating through tree using generators
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
/// iterate through tree using geneartors !/// | |
/// setup /// | |
class Comment { | |
constructor(content, children) { | |
this.content = content; | |
this.children = children; | |
} | |
*[Symbol.iterator]() { | |
yield this.content; | |
for (let child of this.children) { | |
yield* child; | |
} | |
} | |
} | |
const children = [ | |
new Comment("good comment", []), | |
new Comment("bad comment", []), | |
new Comment("meh", []), | |
]; | |
const tree = new Comment("Great post!", children) | |
//// end set up /////// | |
const treeVals = []; | |
for (let value of tree) { | |
treeVals.push(value); | |
} | |
console.log(tree); | |
/* | |
Comment { | |
content: 'Great post!', | |
children: | |
[ Comment { content: 'good comment', children: [] }, | |
Comment { content: 'bad comment', children: [] }, | |
Comment { content: 'meh', children: [] } | |
] | |
} | |
*/ | |
console.log(treeVals); // [ 'Great post!', 'good comment', 'bad comment', 'meh' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment