Skip to content

Instantly share code, notes, and snippets.

@misstonbon
Last active July 10, 2018 03:21
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 misstonbon/83f8455b73646c01f553d073a8c94129 to your computer and use it in GitHub Desktop.
Save misstonbon/83f8455b73646c01f553d073a8c94129 to your computer and use it in GitHub Desktop.
Iterating through tree using generators
/// 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