Last active
August 19, 2019 14:58
-
-
Save anatooly/b83940e827ca36c2d46cf948d1daf019 to your computer and use it in GitHub Desktop.
ES5 generator like ES6 yeald & *foo
This file contains hidden or 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 foo() { | |
function nextState(v) { | |
switch (state) { | |
case 0: | |
state++; | |
return 42; // yield | |
case 1: | |
state++; | |
x = v; // yield ended | |
console.log(x); | |
return undefined; | |
// not need state 2 | |
} | |
} | |
var state = 0, x; | |
return { | |
next: function(v) { | |
var ret = nextState(v); | |
return {value: ret, done: (state === 2)}; | |
} | |
// missed method return() & throw() | |
} | |
} | |
var it = foo(); | |
it.next(); // {value: 42, done: false} | |
it.next(10); // {value: undefined, done: true} | |
/// | |
function *foo() { | |
yield 1; | |
yield 2; | |
yield 3; | |
} | |
for (var v of foo()) { // need iterator | |
console.log(v); | |
} | |
// 1 2 3 | |
var it = foo(); | |
it.next(); // {value: 1, done: false} | |
it.next(); // {value: 2, done: false} | |
it.next(); // {value: 3, done: false} | |
it.next(); // {value: undefined, done: true} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment