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

Array#filterMap #12

Open
lukescott opened this issue Feb 27, 2020 · 1 comment
Open

Array#filterMap #12

lukescott opened this issue Feb 27, 2020 · 1 comment

Comments

@lukescott
Copy link

lukescott commented Feb 27, 2020

With flatMap added with flat to reduce iterations and allocations, it would be nice to have an accompanying filterMap method as well. I often find filter and map used together.

Something like this:

[{active: true, label: "foo"}, {active: true, label: "bar"}]
  .filter(v => v.active)
  .map(v => v.label)

Could be written as:

[{active: true, label: "foo"}, {active: true, label: "bar"}]
  .filterMap(v => v.active && v.label)
@jridgewell
Copy link
Member

This is actually possible via flatMap:

array.flatMap(v => {
  if (!v.active) {
    // Returning an empty array here is equivalent to filtering out the element.
    return [];
  }

  // Returning a single element array with the mapped value keeps the element.
  return [v.label];
});

Exposing an API like this would have to deal with choosing a value that represents "filter this out". Is it false? What if I wanted to map to boolean values?

flatMap's wrapping arrays sidestep this, since it's not the return value but the value's length that differentiates it.

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

2 participants