javascript - 如何组合两个生成器序列?
问题描述
给定两个序列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");
解决方案
最简单的解决方案是再次使用生成器函数语法:
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");
推荐阅读
- java - 合并排序算法没有完全合并。数组的右侧未与左侧合并
- reactjs - 没有“访问控制允许来源”?
- javascript - Jquery选择更改
- json - CakePHP 3:RESTful API 中的异常处理/序列化
- ios - 有没有办法记录应用程序输出的所有声音?
- c# - 如何从另一个类更新窗口应用程序中的进度条?
- angular - 将 ion-item 添加到先前的 ion-item 而不是替换它
- vba - VBA 宏中的内存泄漏
- sql-server - SQL相关:对相同类别求和并仅选择第一条记录
- apache-spark - 为什么 Hive/Spark 中的字符串列没有最小/最大统计信息