Skip to content

Instantly share code, notes, and snippets.

@amoilanen
Created February 1, 2021 13:48
Show Gist options
  • Save amoilanen/e1a14c66e5b2c378ea6bfb519e249ddb to your computer and use it in GitHub Desktop.
Save amoilanen/e1a14c66e5b2c378ea6bfb519e249ddb to your computer and use it in GitHub Desktop.
Simple demo of a generator function
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