proposal-iterator-helpers
proposal-iterator-helpers copied to clipboard
fixes #229: flatMap supports returning both iterables and iterators
Fixes #229.
update: Now also fixes #237, aligning flatMap and from.
Iterator.prototype.flatMap and Iterator.from:
- non-Object: throw
- has
Symbol.iterator: call it, get sync iterator, iterate - has callable
"next": assume sync iterator, iterate - otherwise: throw
AsyncIterator.prototype.flatMap and AsyncIterator.from:
- non-Object: throw
- has
Symbol.asyncIterator: call it, get async iterator, async iterate - has
Symbol.iterator: call it, get sync iterator, lift to async iterator, async iterate - has callable
"next": assume async iterator, async iterate - otherwise: throw
This logic could probably be shared with Iterator.from and AsyncIterator.from, no? It's not exactly the same as written, but I think it probably should be the same.
(Other than the inheritance check and wrapping logic.)
@bakkot This PR now updates the from methods to share an implementation with flatMap.
It feels very strange for me to have Iterator.from(string) throw, given that for (let c of string) works. I am (very reluctantly) OK with .flatMap in particular guarding against strings, but I am against Iterator.from doing that guard.
Strings should be considered as iterables since the current option is inconsistent with all the rest cases of the iterators protocol usage.