//Generator函数定义及使用
function* gen() {
yield 1;
yield 2;
return 3;
}
var g = gen();
console.log('还未执行');
for (let item of g) {
console.log(item);
}
console.log('已经执行');
//使用Generator遍历多维数组
console.log('=======================')
var arr = [1, [[2, 3], 4], [5, 6]];
var flat = function* (arr) {
for (let item of arr) {
if (typeof item != 'number') {
yield* flat(item);
} else {
yield item;
}
}
}
for (let item of flat(arr)) {
console.log(item);
}
//使用常规方法遍历多维数组
console.log('=======================')
function flat2(arr) {
var result = [];
for (let item of arr) {
if (typeof item != 'number') {
flat2(item).forEach(childItem => {
result.push(childItem);
})
} else {
result.push(item);
}
}
return result;
}
for (let item of flat2(arr)) {
console.log(item);
}
//next方法带参数
//yield表达式本身没有返回值,或者说总是返回undefined。
//next方法可以带一个参数,该参数就会被当作上一个yield表达式的返回值。
console.log('=======================')
function* f() {
for(var i = 0; true; i++) {
var reset = yield i;
if(reset) { i = -1; }
}
}
var g = f();
console.log(g.next().value)
console.log(g.next().value)
console.log(g.next(true).value)
//Generation内部调用另外一个Generation
console.log('=======================')
function* foo() {
yield 'a';
yield 'b';
}
function* bar() {
yield 1;
for (let f of foo()) {
yield f;
}
yield 2;
}
var b = bar();
for (let item of b) {
console.log(item);
}
//Thunk与Generation流程自动管理
console.log('=======================')
var Thunk = function(fn){
return function(...args){
return function(callback){
fn.call(this,...args,callback);
}
}
};
var Calculate = function(a,b,cb){
var sum = a + b;
cb(sum);
};
var ThunkCalculate = Thunk(Calculate);
var gen = function* (){
var r1 = yield ThunkCalculate(1,2);
console.log(r1);
var r2 = yield ThunkCalculate(3,4);
console.log(r2);
var r3 = yield ThunkCalculate(5,6);
console.log(r3);
};
var run = function(genFn){
var g = genFn();
var next = function(data){
var result = g.next(data);
if(result.done) return;
result.value(next);
}
next();
};
run(gen);
console