Array.prototype.mapOn method

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

On Fri, Oct 27, 2017 at 8:17 AM, Peter Jaszkowiak <p.jaszkow at> 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:

```>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 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;
}, 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))` ^_^)


More information about the es-discuss mailing list