Created
July 3, 2023 16:11
-
-
Save ernestlv/231928f054ab043280391ef3a37547b2 to your computer and use it in GitHub Desktop.
A generator is an iterator function whose body you can slice into many parts by combining a yield / iterator.next() expression.
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
/* | |
* A generator is an iterator function whose body you can slice into many parts by combining a yield / iterator.next() expression. | |
*/ | |
function* iteratorFn(value) { | |
//body does not execute until first iterator.next() is called | |
console.log("before yield!", value); // execute first iterator body slice | |
value = yield yieldFn(value); // stop execution & returns iterator value - resumes execution, after second iterator.next() is called & updates value from arg in iterator.next( arg ) | |
console.log("after yield:", value); // execute second iterator body slice | |
return "I am done!" + value + "second part"; // stops execution & returns final iterator value | |
} | |
function yieldFn(value) { // executed in yield expression | |
console.log("inside yield!!!"); | |
console.log("Works!!!"); | |
console.log(value) | |
return "Hello World!!!" + value; // iterator value | |
} | |
var iterator = iteratorFn("TTT"); // creates iterator object - TTT is passed to first iterator body slide | |
console.log(iterator); | |
var iteratorValue = iterator.next("ZZZ"); // executes first iteratorFn body slice - ZZZ is ignored | |
console.log(iteratorValue); | |
iteratorValue = iterator.next("PPP"); // executes second iterator body slice - PPP is passed to second iterator body slice | |
console.log(iteratorValue); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment