Array.prototype.mapOn method

Tab Atkins Jr. jackalmage at gmail.com
Fri Oct 27 17:14:56 UTC 2017


On Fri, Oct 27, 2017 at 8:17 AM, Peter Jaszkowiak <p.jaszkow at gmail.com> wrote:
>
> Actually flatMap isn't even needed. My question is, why use this over a normal map with a conditional? It doesn't seem to really save any space.


Right. The example given:

```
exampleArray.mapOn(Math.sqrt, Number.isInteger); // [1, 1.414, 3, "A",
"B", "C"];
```

can be written with today's code as just:

```
exampleArray.map(x=>Number.isInteger(x) ? Math.sqrt(x) : x);
```

You're paying only a tiny handful of additional characters for this.

-----------------

And in any case, specializing this use-case to Array.map only isn't
too great. This sort of "conditionally call this function" ability
would be useful more generally, with something like:

```
function onlyIf(cond, func) {
  return (...x)=>cond(...x) ? func(...x) : x;
}
exampleArray.map(onlyIf(Number.isInteger, Math.sqrt));
```

Feel free to write this into your own code.  (Or get super-fancy and
put it on Function.prototype, so you can write
`.map(Math.sqrt.onlyIf(Number.isInteger))` ^_^)

~TJ


More information about the es-discuss mailing list