首页 > 解决方案 > 如何组合两个生成器序列?

问题描述

给定两个序列g1并由g2生成器计算,如何组合它们以便何时g1输出g2

function* gen(x, y, step) {
    while(x < y) {
        x += step;
        yield x;
    }
};

let g1 = gen(1, 10, 1); 
let g2 = gen(1, 10, 2);

//How to merge g1 and g2 so that after g1 is exhasted g2 is shown?
current = g1.next().value;

while(current !== undefined) {
    console.log(current);
    current = g1.next().value;
}

console.log("done");

标签: javascript

解决方案


最简单的解决方案是再次使用生成器函数语法:

function* both() {
  yield* gen(1, 10, 1); 
  yield* gen(1, 10, 2);
}
const g3 = both();
for (const current of g3)
  console.log(current);
console.log("done");

推荐阅读