Skip to content

Instantly share code, notes, and snippets.

@nodew
Created August 22, 2017 13:24
Show Gist options
  • Save nodew/03374200a73183ed202b745110ddc5fd to your computer and use it in GitHub Desktop.
Save nodew/03374200a73183ed202b745110ddc5fd to your computer and use it in GitHub Desktop.
yield test
const slice = Array.prototype.slice;
const isGenerator = (obj) => {
return 'function' == typeof obj.next && 'function' == typeof obj.throw;
}
function isPromise(obj = {}) {
return 'function' == typeof obj.then;
}
function toPromise(obj) {
if (isPromise(obj)) {
return obj;
} else {
return Promise.resolve(obj);
}
}
function co(gen) {
let ctx = this;
let args = slice.call(arguments, 1);
let ret;
return new Promise((resolve, reject) => {
if (typeof gen === 'function') {
gen = gen.apply(ctx, args);
}
if (!gen || typeof gen.next !== 'function') {
return gen;
}
function next(ret) {
if (ret.done) return resolve(ret.value);
toPromise(ret.value).then(value => {
next(gen.next(value));
}).catch(error => {
reject(error);
});
}
next(gen.next());
})
}
co(function* (val) {
let a = yield Promise.resolve(val);
let b = yield Promise.resolve(val + 1);
return a + b;
}, 3).then(r => {
console.log(r, '============ co ==============');
});
console.log('------------------- increment -----------------');
function* inc() {
var g = 0;
while (true) {
g += 1;
yield g;
}
}
const iterator = inc();
const a = iterator.next().value
console.log(a);
console.log(iterator.next(a).value);
console.log('------------------- fibonacci ------------------');
function* fib() {
var a = 1;
var b = 1;
var tmp;
while(true) {
yield a;
tmp = b;
b = a + b;
a = tmp;
}
}
const fibGen = fib();
console.log(fibGen.next().value);
console.log(fibGen.next().value);
console.log(fibGen.next().value);
console.log(fibGen.next().value);
console.log(fibGen.next().value);
console.log(fibGen.next().value);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment