Skip to content

Instantly share code, notes, and snippets.

@jordanrios94
Last active February 3, 2023 02:14
Show Gist options
  • Save jordanrios94/7f1dd720fcd8e68a1af07a4f29382306 to your computer and use it in GitHub Desktop.
Save jordanrios94/7f1dd720fcd8e68a1af07a4f29382306 to your computer and use it in GitHub Desktop.
Generators
// Basic usage of using generators
function *numbers() {
yield 1;
yield 2;
yield* moreNumbers();
yield 6;
yield 7;
}
function *moreNumbers() {
yield 3;
yield 4;
yield 5;
}
const generator = numbers();
let values = [];
for (let value of generator) {
values.push(value);
}
// Log will produces [1,2,3,4,5,6,7]
console.log(values);
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)
]);
// We can now collect all the values of the tree as such
const values = [];
for (let value of tree.printValues()) {
values.push(value);
}
console.log(values);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment