How do you curry any javascript function of arbitrary arity?

前端 未结 5 1954
天命终不由人
天命终不由人 2020-12-19 04:19

Let\'s say I have some function:

function g(a,b,c){ return a + b + c }

And I\'d like to turn it into its \"curried\" form (in quotations si

5条回答
  •  没有蜡笔的小新
    2020-12-19 04:50

    The bind() method on function lets you bind the this inside the function as well as bind extra parameters. So, if you pass null for the this parameter, you can use bind() to curry the parameters into the function.

    function g(a,b,c){ return a + b + c }
    
    var g_1 = g.bind(null, 1);
    console.log(g_1(2, 3)); // Prints 6
    
    var g_1_2 = g.bind(null, 1, 2);
    console.log(g_1_2(3)); // Prints 6
    

    Check Javascript Function bind() for details and interactive examples of using bind() to bind parameters.

提交回复
热议问题