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.

3

2 Answers 2

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 );

2
  • Thanks @Thum Choon Tat for example
    – Tameshwar
    Oct 24, 2017 at 7:55
  • @FelixKling hghi
    – Tameshwar
    May 16, 2018 at 4:26
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.

1
  • @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, 2017 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.