Add multiple variable passed as parameter to function currying

こ雲淡風輕ζ 提交于 2019-12-08 05:58:09

问题


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.


回答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:


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.



来源:https://stackoverflow.com/questions/46903931/add-multiple-variable-passed-as-parameter-to-function-currying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!