Reputation: 1944
Currying functions can be usefull:
function tag(name, value) {
return '<' + name + '>' + value + '</' + name + '>';
}
var strong = tag.bind(undefined, "strong");
strong("text"); // <strong>text</strong>
Now imagine we have to use another function with wrong order of parameters
function otherTag(value, name) {
return '<' + name + '>' + value + '</' + name + '>';
}
How to use bind function to get the same result - create strong tag using otherTag function.
How to curry this function using bind only?
I'm not interested in solution based on wrapping the otherTag function like this:
wrapOtherTag(name, value) {
return otherTag(value, name);
}
What I want to know if it is possible to pass arguments to bind to tell the order of arguments we want to curry.
Upvotes: 1
Views: 485
Reputation:
Write a function to reverse argument order:
function swap(fn) {
return function(a, b) {
return fn(b, a);
};
}
Now just call
swap(otherTag).bind(0, "strong");
Upvotes: 2
Reputation: 10674
You can write your own function to accomplish this.
// Uncurry `this` in `slice`.
var slice = Function.prototype.call.bind(Array.prototype.slice);
function curry(fn, arg, index) {
return function curried(/* ...args */) {
var args = slice(arguments);
args.splice(index, 0, arg);
return fn.apply(this, args);
};
}
var strong = curry(tag, "strong", 0);
strong("text"); // <strong>text</strong>
var otherStrong = curry(otherTag, "strong", 1);
otherStrong("text"); // <strong>text</strong>
Upvotes: 1