Iterator Helpers Chain Lazily Over Generators
Compose map, filter, take, drop, and flatMap directly on generators: unbounded sources stay lazy and only consumed items are produced.
Code
// 迭代器助手方法 (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)]);Output
Captured from a sandboxed run of this snippet in the build pipeline.
[
'id-1:a', 'id-1:b',
'id-2:a', 'id-2:b',
'id-3:a', 'id-3:b',
'id-4:a', 'id-4:b',
'id-5:a', 'id-5:b'
]
[
'id-1-left',
'id-1-right',
'id-2-left',
'id-2-right',
'id-3-left',
'id-3-right'
]
total : 22
[ 'first' ]What the code does
Iteration happens inside for (let n = 1; ; n++) yield 'id-' + n; — everything outside it runs once. There is no validation gate in front of the Error — the throw fires whenever its line runs.
The demo data lives in module-level bindings: pages, pairs, total.
Applying it
The demo output is labeled (total :), so every printed line maps back to its originating operation.
Statements that matter
.reduce((sum, id) => sum + Number(id.slice(3)), 0);
.flatMap((id) => [id + ':a', id + ':b']);
for (let n = 1; ; n++) yield 'id-' + n;
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Is input validated before use?
- There is no validation gate: the `Error` raise happens unconditionally whenever its line executes.
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `pages`, `pairs`, `total`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.