How to curry a function across an unknown number of parameters

后端 未结 5 2068
灰色年华
灰色年华 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:13

    Using a functional approach, you can create a function that "curries" arguments for another function. You will need a way to tell the function to return the value, so in this case, calling the function without passing any arguments will return the result:

    function curry(fn, ...values) {
        return (...next) => (next.length) ? curry(fn, ...values, ...next) : fn(...values);
    }
    

    The cool thing about this function is that you can pass multiple arguments and/or keep invoking the function (1)(2, 3, 4)(5).

    Here's a couple of examples:

    function curry(fn, ...values) {
      return (...next) => (next.length) ? curry(fn, ...values, ...next) : fn(...values);
    }
    
    function multiplyDivide(...args) {
      return args.reduce((total, next, i) => (i % 2) ? (total / next) : (total * next), args.shift());
    }
    
    let x = curry(multiplyDivide)(2)(3, 4)(6)();
    console.log(x);
    
    let y = curry(multiplyDivide)(5, 4, 2)(3);
    y = y(3, 5)(1)();
    console.log(y);

    Of course, this example does hint at just simply overloading the multiplyDivide function and passing your values to that when you're ready:

    function multiplyDivide(...args) {
      return args.reduce((total, next, i) => (i % 2) ? (total / next) : (total * next), args.shift());
    }
    
    const values = [5, 4, 2, 3, 3];
    values.push(5, 1);
    
    console.log(multiplyDivide(...values));

提交回复
热议问题