Created
February 1, 2021 13:48
-
-
Save amoilanen/e1a14c66e5b2c378ea6bfb519e249ddb to your computer and use it in GitHub Desktop.
Simple demo of a generator function
This file contains hidden or 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
function square(x) { | |
return x * x; | |
} | |
function* sumSquares(values) { | |
let result = 0; | |
for (value of values) { | |
const nextIncrement = yield square(value); | |
console.log(`inside sumSquares: ${nextIncrement}`); | |
result += nextIncrement; | |
} | |
return result; | |
} | |
const generator = sumSquares([1, 2, 3, 4, 5]) | |
let result = generator.next(); | |
console.log(result); | |
while (!result.done) { | |
result = generator.next(result.value); | |
console.log(result); | |
} | |
console.log(result.value); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment