proposal-iterator-helpers icon indicating copy to clipboard operation
proposal-iterator-helpers copied to clipboard

fixes #229: flatMap supports returning both iterables and iterators

Open michaelficarra opened this issue 3 years ago • 4 comments

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

michaelficarra avatar Sep 09 '22 23:09 michaelficarra

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 avatar Sep 12 '22 19:09 bakkot

@bakkot This PR now updates the from methods to share an implementation with flatMap.

michaelficarra avatar Sep 23 '22 22:09 michaelficarra

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.

bakkot avatar Sep 26 '22 20:09 bakkot

Strings should be considered as iterables since the current option is inconsistent with all the rest cases of the iterators protocol usage.

zloirock avatar Oct 11 '22 02:10 zloirock