Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demystifying Async Programming in Javascript - Generator internals adder state machine
function adder(initialValue) {
let state = 'initial';
let done = false;
let sum = initialValue;
function go(input) {
let result;
switch (state) {
case 'initial':
result = initialValue;
state = 'loop';
break;
case 'loop':
sum += input;
result = sum;
state = 'loop';
break;
default:
break;
}
return {done: done, value: result};
}
return {
next: go
}
}
function runner() {
const add = adder(0);
console.log(add.next()); // 0
console.log(add.next(1)); // 1
console.log(add.next(2)); // 3
console.log(add.next(3)); // 6
}
runner();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.