Last active
February 3, 2023 02:14
-
-
Save jordanrios94/7f1dd720fcd8e68a1af07a4f29382306 to your computer and use it in GitHub Desktop.
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
// 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); |
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
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