What is the most elegant way to convert a method to a curried function, and is there support for this in libs like Underscore/Lo-dash or Ramda?
For a fixed number of arguments I'm doing this right now:
var fn2 = _.curry(function (m, a1, a2, obj) {
return obj[m].call(obj, a1, a2);
});
which allows for code like:
var a2b = fn2('replace', 'a', 'b')
a2b('abc')
=> 'bbc'
as well as:
var nl2_ = fn2('replace', '<br>')
nl2_('\n', 'some<br>html')
=> 'some\nhtml'
You can easily extend your approach for methods with arbitrary arity:
function curryMethod(m, a) {
if (a !== ~~a) a = m.length;
return _.curry(function() {
return m.apply(arguments[a], Array.prototype.slice.call(arguments, 0, -1));
}, a+1);
}
> var replace = curryMethod(String.prototype.replace)
> replace("a", "b", "abc")
"bbc"
> var a2b = replace("a", "b")
> a2b("abc")
"bbc"
Since you also have asked about Ramda, I've only quickly scanned their API but found the R.invoker function which seems to be exactly what you're looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With