假设我有一台发电机:
function* source() {
yield "hello"; yield "world";
}
我创建了iterable,使用for循环进行迭代,然后在迭代器完全完成之前退出循环(返回完成)。
function run() {
for (let item of source()) {
console.log(item);
break;
}
}
问题:如何从迭代方面找出迭代器提前终止?
如果您尝试直接在生成器本身中执行此操作,似乎没有任何反馈:
function* source2() {
try {
let result = yield "hello";
console.log("foo");
} catch (err) {
console.log("bar");
}
}
...既未记录“foo”也未记录“bar”。
答案 0 :(得分:3)
我注意到typescript将Iterator
(lib.es2015)定义为:
interface Iterator<T> {
next(value?: any): IteratorResult<T>;
return?(value?: any): IteratorResult<T>;
throw?(e?: any): IteratorResult<T>;
}
我拦截了这些方法和记录调用,看起来如果迭代器提前终止 - 至少通过for-loop
- 那么调用return
方法。 如果消费者抛出错误,也会调用它。如果允许循环完全迭代,则迭代器return
不被调用。
Return
hack 所以,我做了一些hack来允许捕获另一个可迭代 - 所以我不必重新实现迭代器。
function terminated(iterable, cb) {
return {
[Symbol.iterator]() {
const it = iterable[Symbol.iterator]();
it.return = function (value) {
cb(value);
return { done: true, value: undefined };
}
return it;
}
}
}
function* source() {
yield "hello"; yield "world";
}
function source2(){
return terminated(source(), () => { console.log("foo") });
}
for (let item of source2()) {
console.log(item);
break;
}
它有效!
你好 FOO
删除break
,然后获得:
你好 世界
yield
在输入这个答案时,我意识到更好的问题/解决方案是找出原始生成器方法中的 。
我能看到将信息传递回原始可迭代的唯一方法是使用next(value)
。因此,如果我们选择一些唯一值(比如Symbol.for("terminated")
)来表示终止,我们会更改上述返回黑客以致电it.next(Symbol.for("terminated"))
:
function* source() {
let terminated = yield "hello";
if (terminated == Symbol.for("terminated")) {
console.log("FooBar!");
return;
}
yield "world";
}
function terminator(iterable) {
return {
[Symbol.iterator]() {
const it = iterable[Symbol.iterator]();
const $return = it.return;
it.return = function (value) {
it.next(Symbol.for("terminated"));
return $return.call(it)
}
return it;
}
}
}
for (let item of terminator(source())) {
console.log(item);
break;
}
成功!
你好 FooBar的!
Return
如果你链接一些额外的变换迭代器,那么return
调用将通过它们全部级联:
function* chain(source) {
for (let item of source) { yield item; }
}
for (let item of chain(chain(terminator(source())))) {
console.log(item);
break
}
你好 FooBar的!
我已经包含了上述解决方案as a package。它同时支持[Symbol.iterator]
和[Symbol.asyncIterator]
。异步迭代器的情况对我来说特别有意义,特别是当某些资源需要正确处理时。
答案 1 :(得分:3)
有一种更简单的方法来做到这一点:使用 finally 块。
function *source() {
let i;
try {
for(i = 0; i < 5; i++)
yield i;
}
finally {
if(i !== 5)
console.log(' terminated early');
}
}
console.log('First:')
for(const val of source()) {
console.log(` ${val}`);
}
console.log('Second:')
for(const val of source()) {
console.log(` ${val}`);
if(val > 2)
break;
}
...收益:
First:
0
1
2
3
4
Second:
0
1
2
3
terminated early
答案 2 :(得分:0)
我遇到了类似的问题,需要弄清楚迭代器何时提前终止。公认的答案确实很聪明,并且可能是一般性地解决问题的最佳方法,但我认为这种解决方案也可能对其他用例有用。
例如,您有一个无限的可迭代对象,例如MDN's Iterators and Generators docs中描述的斐波那契序列。
在任何种类的循环中,都需要设置一个条件以尽早脱离循环,就像已经给出的解决方案一样。但是,如果要分解可迭代对象以创建值数组怎么办?在这种情况下,您希望限制迭代次数,实际上是在可迭代对象上设置最大长度。
为此,我编写了一个名为limitIterable
的函数,该函数将一个可迭代的迭代限制和一个可选的回调函数作为参数,以防迭代器提前终止。返回值是使用Immediately Invoked (Generator) Function Expression创建的Generator对象(既是迭代器又是可迭代)。
执行生成器时,无论是在for..of循环中,使用解构还是通过调用next()方法,它都会检查是查看iterator.next().done === true
还是iterationCount < iterationLimit
。在像斐波那契数列这样的无限迭代的情况下,后者将始终导致while循环退出。但是,请注意,也可以将迭代限制设置为大于某个有限可迭代的长度,并且一切仍然可以进行。
无论哪种情况,一旦退出while循环,都会检查最新结果以查看迭代器是否完成。如果是这样,将使用原始的Iterable返回值。如果没有,则执行可选的回调函数并将其用作返回值。
请注意,此代码还允许用户将值传递到next()
,而后者又将传递给原始的可迭代对象(请参见示例中使用MDN的fibonacci序列的示例)。除了在回调函数中设置的迭代限制之外,它还允许对next()
的其他调用。
运行代码片段以查看一些可能的用例的结果!以下是limitIterable
函数代码:
function limitIterable(iterable, iterationLimit, callback = (itCount, result, it) => undefined) {
// callback will be executed if iterator terminates early
if (!(Symbol.iterator in Object(iterable))) {
throw new Error('First argument must be iterable');
}
if (iterationLimit < 1 || !Number.isInteger(iterationLimit)) {
throw new Error('Second argument must be an integer greater than or equal to 1');
}
if (!(callback instanceof Function)) {
throw new Error('Third argument must be a function');
}
return (function* () {
const iterator = iterable[Symbol.iterator]();
// value passed to the first invocation of next() is always ignored, so no need to pass argument to next() outside of while loop
let result = iterator.next();
let iterationCount = 0;
while (!result.done && iterationCount < iterationLimit) {
const nextArg = yield result.value;
result = iterator.next(nextArg);
iterationCount++;
}
if (result.done) {
// iterator has been fully consumed, so result.value will be the iterator's return value (the value present alongside done: true)
return result.value;
} else {
// iteration was terminated before completion (note that iterator will still accept calls to next() inside the callback function)
return callback(iterationCount, result, iterator);
}
})();
}
function limitIterable(iterable, iterationLimit, callback = (itCount, result, it) => undefined) {
// callback will be executed if iterator terminates early
if (!(Symbol.iterator in Object(iterable))) {
throw new Error('First argument must be iterable');
}
if (iterationLimit < 1 || !Number.isInteger(iterationLimit)) {
throw new Error('Second argument must be an integer greater than or equal to 1');
}
if (!(callback instanceof Function)) {
throw new Error('Third argument must be a function');
}
return (function* () {
const iterator = iterable[Symbol.iterator]();
// value passed to the first invocation of next() is always ignored, so no need to pass argument to next() outside of while loop
let result = iterator.next();
let iterationCount = 0;
while (!result.done && iterationCount < iterationLimit) {
const nextArg = yield result.value;
result = iterator.next(nextArg);
iterationCount++;
}
if (result.done) {
// iterator has been fully consumed, so result.value will be the iterator's return value (the value present alongside done: true)
return result.value;
} else {
// iteration was terminated before completion (note that iterator will still accept calls to next() inside the callback function)
return callback(iterationCount, result, iterator);
}
})();
}
// EXAMPLE USAGE //
// fibonacci function from:
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Advanced_generators
function* fibonacci() {
let fn1 = 0;
let fn2 = 1;
while (true) {
let current = fn1;
fn1 = fn2;
fn2 = current + fn1;
let reset = yield current;
if (reset) {
fn1 = 0;
fn2 = 1;
}
}
}
console.log('String iterable with 26 characters terminated early after 10 iterations, destructured into an array. Callback reached.');
const itString = limitIterable('abcdefghijklmnopqrstuvwxyz', 10, () => console.log('callback: string terminated early'));
console.log([...itString]);
console.log('Array iterable with length 3 terminates before limit of 4 is reached. Callback not reached.');
const itArray = limitIterable([1,2,3], 4, () => console.log('callback: array terminated early?'));
for (const val of itArray) {
console.log(val);
}
const fib = fibonacci();
const fibLimited = limitIterable(fibonacci(), 9, (itCount) => console.warn(`Iteration terminated early at fibLimited. ${itCount} iterations completed.`));
console.log('Fibonacci sequences are equivalent up to 9 iterations, as shown in MDN docs linked above.');
console.log('Limited fibonacci: 11 calls to next() but limited to 9 iterations; reset on 8th call')
console.log(fibLimited.next().value);
console.log(fibLimited.next().value);
console.log(fibLimited.next().value);
console.log(fibLimited.next().value);
console.log(fibLimited.next().value);
console.log(fibLimited.next().value);
console.log(fibLimited.next().value);
console.log(fibLimited.next(true).value);
console.log(fibLimited.next().value);
console.log(fibLimited.next().value);
console.log(fibLimited.next().value);
console.log('Original (infinite) fibonacci: 11 calls to next(); reset on 8th call')
console.log(fib.next().value);
console.log(fib.next().value);
console.log(fib.next().value);
console.log(fib.next().value);
console.log(fib.next().value);
console.log(fib.next().value);
console.log(fib.next().value);
console.log(fib.next(true).value);
console.log(fib.next().value);
console.log(fib.next().value);
console.log(fib.next().value);