示例工程 06-arrays-iterables-generators
06-arrays-iterables-generators/04-generators/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— 生成器:惰性序列、双向通信、yield* 委托、提前退出清理
export function* naturals() {
let n = 0;
while (true) yield n++;
}
export function take(iterable, count) {
const out = [];
for (const value of iterable) {
if (out.length >= count) break;
out.push(value);
}
return out;
}
export function* mapIter(iterable, fn) {
for (const value of iterable) yield fn(value);
}
export function* fibonacci() {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
export function* delegate() {
yield 1;
yield* [2, 3];
yield 4;
}
export function twoWay() {
function* g() {
const x = yield 'first';
const y = yield x * 2;
return x + y;
}
const it = g();
return { first: it.next(), second: it.next(10), third: it.next(5) };
}
export function cleanupOnBreak() {
const log = [];
function* g() {
try {
yield 1;
yield 2;
yield 3;
} finally {
log.push('finally');
}
}
for (const value of g()) {
if (value === 2) break;
}
return log;
}
export function generatorIsIterable() {
function* g() {
yield 1;
}
const it = g();
return { selfIterable: it[Symbol.iterator]() === it, hasNext: typeof it.next === 'function' };
}
export function run(log = console.log) {
const squares = take(mapIter(naturals(), (n) => n * n), 4);
const fibs = take(fibonacci(), 8);
const tw = twoWay();
const rows = [
['自然数取前 10 个', JSON.stringify(take(naturals(), 10))],
['平方映射(惰性)取 4 个', JSON.stringify(squares)],
['斐波那契前 8 个', JSON.stringify(fibs)],
['yield* 委托', JSON.stringify([...delegate()])],
['双向 next(value)', JSON.stringify([tw.first, tw.second, tw.third])],
['break 触发 finally', JSON.stringify(cleanupOnBreak())],
['生成器对象是自迭代的', JSON.stringify(generatorIsIterable())],
];
log('场景 => 结果');
for (const [label, value] of rows) log(`${label} => ${value}`);
log('-'.repeat(50));
log('要点:生成器函数调用后不执行函数体,返回迭代器;每次 next() 推进到下一个 yield,惰性求值。');
return rows;
}