Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mightyguava/26a81be5b11e084704e13f5bcdf059cf to your computer and use it in GitHub Desktop.
Save mightyguava/26a81be5b11e084704e13f5bcdf059cf to your computer and use it in GitHub Desktop.
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