有没有办法减少与其调用者通信的无限生成器中的产量数量?
Is there a way to reduce the number of yields in an infinite generator communicating with its caller?
在关于 Javascript 生成器的讨论中,有人设计了一个有趣的函数:
function *foo() {
var y = 1;
while(true) yield (y = (y * (yield)));
}
现在,可以通过以下方式使用此功能:
var results = [];
var bar = foo();
bar.next();
results.push(bar.next(2));
bar.next();
results.push(bar.next(2));
bar.next();
results.push(bar.next(2));
bar.next();
results.push(bar.next(2));
正如我们所见,为了获得下一个产品,我们需要调用 next
两次。问题是:这能以某种方式通过一次 yield 解决吗?
while(true) y *= yield y;
只输出 y,然后将 y 乘以它的结果。
function *foo() {
let y = 1;
while(true) y *= yield y;
}
const bar = foo();
bar.next();
console.log(bar.next(2).value);
console.log(bar.next(2).value);
console.log(bar.next(2).value);
在关于 Javascript 生成器的讨论中,有人设计了一个有趣的函数:
function *foo() {
var y = 1;
while(true) yield (y = (y * (yield)));
}
现在,可以通过以下方式使用此功能:
var results = [];
var bar = foo();
bar.next();
results.push(bar.next(2));
bar.next();
results.push(bar.next(2));
bar.next();
results.push(bar.next(2));
bar.next();
results.push(bar.next(2));
正如我们所见,为了获得下一个产品,我们需要调用 next
两次。问题是:这能以某种方式通过一次 yield 解决吗?
while(true) y *= yield y;
只输出 y,然后将 y 乘以它的结果。
function *foo() {
let y = 1;
while(true) y *= yield y;
}
const bar = foo();
bar.next();
console.log(bar.next(2).value);
console.log(bar.next(2).value);
console.log(bar.next(2).value);