Fix Functional Methods
While I don’t go in for puzzlers as interview questions anymore (yes, I was that guy), I enjoy a good brain
teaser now and again. JavaScript Puzzlers! reminded me that in my
attempt to tame native functions, I was missing a few. Namely, parseInt
(a binary function with no
receiver object and an often forgotten second parameter) and Math.pow
(a binary function with a more helpful
second parameter) functions.
Like the leave
example from
Take or Leave Functional Programming,
the following code will have problems with hidden arguments passed by map.
What if we change map
instead of guarding its arguments the way leave
did.
While that works for the example code, you should always pass the radix parameter.
So, this begs the question, “Flip or fix?” Both of these methods have binary signatures, which means I can tame them with a flip/curry approach or a more general fix. Flip appears commonly in functional libraries. The general utility of flipping parameters around seems helpful, but I can’t imagine using it very often beyond binary functions. Fixing a parameter works like a selective version of partial application wherein a specific argument takes the place of a particular parameter.
While leave
, like mapUnary
can help prevent hidden arguments leaking into the predicate,
it will not prevent other errors caused by not passing the radix argument. To flip and curry the arguments
we need to do something like this:
I don’t think I would add this to _part_ because it needs to create reverse. Besides, it still breaks:
Ok, fine. What if we flip the args
using some ES6 goodness?
That makes some sense, it really helps having ES6 to make it happen, and it will not create a new method internally. I could see adding it to _part_ except it will still not work for the original problem!
On the other hand, fix
could work like this:
While that fixes the problem (pun intended), I will refrain from adding it to the library because it creates
splice_
without exposing it. But I think you can see, fix
, the more general solution, works better
than flip
. Performance tests anyone?