实现说明
for (let n = 1; ; n++) yield 'id-' + n; 反复执行,循环体之外没有别的重复。Error 不与任何输入检查绑定:执行到达那一行就会触发。
顶层就这几处状态:pages、pairs、total。
常见问题
输入在使用前会被校验吗?
没有校验门槛:只要那一行执行,Error 的 raise 就会无条件发生。
复制和运行之间有安装步骤吗?
没有。从复制到运行之间没有别的要做。 跨调用保留的状态放在这些顶层绑定里:pages、pairs、total。
核心语句
.reduce((sum, id) => sum + Number(id.slice(3)), 0);
.flatMap((id) => [id + ':a', id + ':b']);
for (let n = 1; ; n++) yield 'id-' + n;
代码示例
// 迭代器助手方法 (iterator helpers) 直接链在生成器上,全程惰性
function* ids() {
for (let n = 1; ; n++) yield 'id-' + n;
}
// flatMap 展开一对多关系;take 限定上限;无界生成器不会失控
const pages = ids()
.take(5)
.flatMap((id) => [id + ':a', id + ':b']);
console.log([...pages]);
// 转置成对再来一遍:同一链路换个形状
const pairs = ids()
.take(3)
.flatMap(function* (id) {
yield id + '-left';
yield id + '-right';
});
console.log([...pairs]);
// filter/drop/reduce 组合:先丢弃前 2 个,再过滤,最后聚合
const total = ids()
.drop(2)
.take(5)
.filter((id) => id.endsWith('3') === false)
.reduce((sum, id) => sum + Number(id.slice(3)), 0);
console.log('total :', total);
// 惰性验证:take(1) 只从生成器拉一个元素,其余从未执行
function* probe() {
yield 'first';
throw new Error('should never run');
}
console.log([...probe().take(1)]);