Created
March 12, 2017 18:58
-
-
Save mightyguava/b2eb89638ac9fc055b2ac2d9fcd67974 to your computer and use it in GitHub Desktop.
Demystifying Async Programming in Javascript - Generator internals reverting adder
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
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