Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How will flatMap handle undefined returns? #17

Open
benlesh opened this issue Mar 19, 2024 · 6 comments
Open

How will flatMap handle undefined returns? #17

benlesh opened this issue Mar 19, 2024 · 6 comments

Comments

@benlesh
Copy link

benlesh commented Mar 19, 2024

I'm a little fuzzy on how this (or iterator helpers) will handle undefined returns. Array#flatMap will just add an undefined value to the output flattened array. I assume the same is true here?

const result = someAsyncIterator.flatMap(v => { });

for await (const value of result) {
  console.log(value); // just prints `undefined` over and over.
}
@bakkot
Copy link
Collaborator

bakkot commented Mar 19, 2024

It throws if the mapper returns any non-iterator/iterable value, including undefined. (As a separate special case, it also throws if the mapper returns a string.)

You can try it today in Chrome 122+: [0].values().flatMap(x => [1, 2]).toArray().

@bakkot
Copy link
Collaborator

bakkot commented Mar 19, 2024

(For async helpers, it will await the value first, and also allows async iterables. But otherwise it's the same, and since await undefined is not an iterator nor a sync or async iterable, it will throw.)

@conartist6
Copy link

It's unfortunate that mapper returning a string will error out, i.e. that flatmap works on almost all iterables but not all of them

@ljharb
Copy link
Member

ljharb commented Mar 19, 2024

I would consider that an intentional design decision; it's very harmful that strings are directly iterable and in new APIs we're generally requiring the iterable to be an object specifically to exclude strings.

@bakkot
Copy link
Collaborator

bakkot commented Mar 19, 2024

That's very much intentional. See discussion in tc39/proposal-iterator-helpers#244, tc39/proposal-iterator-helpers#229, etc.

Wanting to treat a string as iterable for purposes of flatMap is such a weird thing to do that it seems fine/good that you have to explicitly signal that you really did intend to do so (e.g. by returning string[Symbol.iterator]()) rather than it happening by default.

In any case, that's off-topic for this issue.

@conartist6
Copy link

Oh I'm sure it's intentional, yeah. I understand why too. Sorry, I swear I'm not trying to stir up controversy everywhere I go today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants