1

How can I achieve these scenarios using function currying?

add(3,4)(3)
add(3)(4)(3)
add(3)(4,3)

I have read so many blogs not able to find this kind of scenario. can someone help me on this.

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
Tameshwar
  • 789
  • 1
  • 10
  • 17

2 Answers2

1

Something like this?

var total = 0;
function add(){
    // Add up every argument received
    for (var i in arguments)
        total += arguments[i];
        
    return add;
}

add(3,4)(3);
console.log(total);

add(3)(4)(3);
console.log(total);

add(3)(4,3);
console.log(total);

Update

If you do not want the function to depend on global variable, save the value as an attribute of add function instead

function add(){
    // Add up every argument received
    for (var i in arguments)
        add.total += arguments[i];
        
    return add;
}

add.total = 0;
add.toString = function(){
  var total = add.total;
  
  add.total = 0;
  
  return total;
};

var sum1 = add(3,4)(3);
alert( sum1 );

var sum2 = add(3)(4)(3);
alert( sum2 );

var sum3 = add(3)(4,3);
alert( sum3 );
Community
  • 1
  • 1
Thum Choon Tat
  • 3,084
  • 1
  • 22
  • 24
0

I see two currying scenarios here:

1.

add(3,4)(3)
add(3)(4,3)

and

2.

add(3)(4)(3)

The first one you can address with:

function add() {
    const args1 = Array.prototype.slice.call(arguments);
    return function() {
        const args2 = Array.prototype.slice.call(arguments);
        return args1.concat(args2).reduce(function(a, i) { return a + i });
    }
}

The second one with:

function add() {
    const args1 = Array.prototype.slice.call(arguments);
    return function() {
        const args2 = Array.prototype.slice.call(arguments);
        return function() {
            const args3 = Array.prototype.slice.call(arguments);
            return args1.concat(args2).concat(args3).reduce(function(a, i) { return a + i });
        }
    }
}

I did not find a solution to have a function which tackles both at the same time.

gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
  • **@gil.fernandes**: yes, you are correct **read the articles posted by Felix Kling** . Possible duplicate of How can I pre-set arguments in JavaScript function call? (Partial Function Application) – Felix Kling yesterday – Tameshwar Oct 25 '17 at 12:28