Using as (curried) methods in JavaScript
What's the most elegant way to convert a method to a curried function, and is there support for that in libs like Underscore / Lo-dash or Ramda?
For a fixed number of arguments, I am doing this right now:
var fn2 = _.curry(function (m, a1, a2, obj) {
return obj[m].call(obj, a1, a2);
});
which allows code to be used like:
var a2b = fn2('replace', 'a', 'b')
a2b('abc')
=> 'bbc'
and:
var nl2_ = fn2('replace', '<br>')
nl2_('\n', 'some<br>html')
=> 'some\nhtml'
+3
source to share
1 answer
You can easily extend your approach to methods with arbitrary clarity:
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 asked about Ramda, I only took a quick look at their API but found a R.invoker
function that seems to be exactly what you are looking for.
+4
source to share