tc39 / proposal-iterator-helpers

Methods for working with iterators in ECMAScript

Home Page:https://tc39.es/proposal-iterator-helpers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

some/every/find cannot close Array Iterator

woess opened this issue · comments

According to README.md, the iterator is consumed when some is called, and this is illustrated by the following example:

const iter = [1, 2, 3].values();

iter.some(v => v > 1); // true
iter.some(v => true); // false, iterator is already consumed.

However, Array Iterator objects do not have a return method and therefore cannot be closed, so this example does not work as indicated. Subsequent calls to some will simply continue iterating until the iterator is actually consumed. Similarly, every and find methods will not always consume iterators that don't support closing.

It's unclear to me if this is simply a wrong example or something that should be addressed in the proposal (e.g. by adding %ArrayIteratorPrototype%.return()), but either way, it should be clarified.

Huh, I did not realize array iterators couldn't be closed. That's pretty weird:

let it = [0, 1, 2].values();
for (let a of it) { console.log(a); break; } // prints 0
for (let a of it) { console.log(a); break; } // prints 1
for (let a of it) { console.log(a); break; } // prints 2

Contrast generators:

let it = (function* (){ yield* [0, 1, 2]; })();
for (let a of it) { console.log(a); break; } // prints 0
for (let a of it) { console.log(a); break; } // does nothing
for (let a of it) { console.log(a); break; } // does nothing

I wonder if we could get away with changing the existing built-in iterators so they can be closed, to match generators. Possibly not at this point.

Anyway, yes, the example is wrong and should be corrected.