Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do currying with UnderscoreJS?

I am a bit experimenting with _.bind(...). I see how to force a function context with bind, but don't yet see how to do currying.

What I try is this:

 add = function(number) { this.sum = this.sum + number; }
 add5 = _.bind(add, { sum: 0 }, 5)

However, calling add5(), or add5(5) seems not to have some effects.

Any clues how to do wrap the arguments such that the context is preserved from one call to another?

like image 691
poseid Avatar asked May 13 '13 11:05

poseid


1 Answers

Probably you want to do partial application, not currying/schönfinkeling. Underscore has the _.partial function for this:

function add(a, b) { return a+b; }
var add5 = _.partial(add, 5);

You can as well use _.bind, and it has some effects. For example:

var add5 = _.bind(add, null /*context is irrelevant*/, 5);
add5(3); // returns 8

Yet, your function did not return anything, and the context which you did change was not accessible. However:

var ctx1 = {sum: 0};
function add(a) { this.sum += a; } // returns nothing!
var addto1 = _.bind(add, ctx1);
addto1(5); // undefined
ctx1; // {sum: 5}

var add5to1 = _.bind(add, ctx1, 5);
add5to1(); // undefined
ctx1; // {sum: 10}

var ctx2 = {sum: 5};
add3to2 = _.bind(add, ctx2, 3);
add3to2(); // undefined
ctx2; // {sum: 8}
like image 193
Bergi Avatar answered Sep 21 '22 14:09

Bergi