How to curry a function across an unknown number of parameters

后端 未结 5 2088
灰色年华
灰色年华 2020-12-06 18:40

Say I have a function called multiplyDivide

If I were to call multiplyDivide(2)(3)(4)(6) it would be equivalent to 2 * 3 / 4 * 6

5条回答
  •  庸人自扰
    2020-12-06 19:14

    This is in fact a very good question...

    Currying is one of the most fundamental aspects of functional programming languages where you can pass around and return functions. JS being a functional programming language at some level, should be able to perform this operation.

    So just like the one in your question one might want to curry an indefinitely many argument function for this or that reasons.

    OK let your function be

    function multiplyDivide (n,m,o,p){
      return n * m / o * p;
    }
    

    Then a way of implementing a utility curry function to obtain the curried version of any given function would be as follows;

    var curry = f => f.length ? (...a) => curry(f.bind(f,...a)) : f(),
    

    So let's see it in action

    function multiplyDivide (n,m,o,p){
          return n * m / o * p;
        }
    
    var curry = f => f.length ? (...a) => curry(f.bind(f,...a)) : f(),
        f     = curry(multiplyDivide);
     
     res1 = f(4,5,2,10),
     res2 = f(4)(5,2,10),
     res3 = f(4)(5)(2,10),
     res4 = f(4)(5)(2)(10),
     res5 = f(4,5)(2,10),
     res6 = f(4,5)(2)(10),
     res7 = f(4,5,2)(10),
     res8 = f(4,5)(2,10);
    console.log(res1,res2,res3,res4,res5,res6,res7,res8);

    There might be simpler ways but this is what i could have come up with.

提交回复
热议问题