Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mightyguava/b2eb89638ac9fc055b2ac2d9fcd67974 to your computer and use it in GitHub Desktop.
Save mightyguava/b2eb89638ac9fc055b2ac2d9fcd67974 to your computer and use it in GitHub Desktop.
Demystifying Async Programming in Javascript - Generator internals reverting adder
function* adder(initialValue) {
let sum = initialValue;
let lastSum = initialValue;
let temp;
while (true) {
try {
temp = sum;
sum += yield sum;
lastSum = temp;
} catch (e) {
sum = lastSum;
}
}
}
const add = adder(0);
console.log(add.next()); // 0
console.log(add.next(1)); // 1
console.log(add.next(2)); // 3
console.log(add.throw(new Error('BOO)!'))); // 1
console.log(add.next(4)); // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment