Variadic curried sum function

前端 未结 16 1824
清酒与你
清酒与你 2020-11-22 06:33

I need a js sum function to work like this:

sum(1)(2) = 3
sum(1)(2)(3) = 6
sum(1)(2)(3)(4) = 10 
etc.

I heard it can\'t be done. But heard

相关标签:
16条回答
  • 2020-11-22 07:16

    Not sure if I understood what you want, but

    function sum(n) {
      var v = function(x) {
        return sum(n + x);
      };
    
      v.valueOf = v.toString = function() {
        return n;
      };
    
      return v;
    }
    
    console.log(+sum(1)(2)(3)(4));

    JsFiddle

    0 讨论(0)
  • 2020-11-22 07:17

    Here is another functional way using an iterative process

    const sum = (num, acc = 0) => {
        if (!num) return acc;
        return x => sum(x, acc + num)
    }
    
    sum(1)(2)(3)()
    

    and one-line

    const sum = (num, acc = 0) => !num ? acc : x => sum(x, acc + num)
    
    sum(1)(2)(3)()
    
    0 讨论(0)
  • 2020-11-22 07:18

    Another slightly shorter approach:

     const sum = a => b => b? sum(a + b) : a;
    

    Usable as:

    console.log(
      sum(1)(2)(),
      sum(3)(4)(5)()
    );
    
    0 讨论(0)
  • 2020-11-22 07:20

    Here is a solution that uses ES6 and toString, similar to @Vemba

    function add(a) {
      let curry = (b) => {
        a += b
        return curry
      }
      curry.toString = () => a
      return curry
    }
    
    console.log(add(1))
    console.log(add(1)(2))
    console.log(add(1)(2)(3))
    console.log(add(1)(2)(3)(4))

    0 讨论(0)
  • 2020-11-22 07:20

    New ES6 way and is concise.

    You have to pass empty () at the end when you want to terminate the call and get the final value.

    const sum= x => y => (y !== undefined) ? sum(x + y) : x;
    

    call it like this -

    sum(10)(30)(45)();
    
    0 讨论(0)
  • 2020-11-22 07:21
    function add(a) {
        let curry = (b) => {
            a += b
            return curry;
        }
        curry[Symbol.toPrimitive] = (hint) => {
            return a;
        }
        return curry
    }
    
    console.log(+add(1)(2)(3)(4)(5));        // 15
    console.log(+add(6)(6)(6));              // 18
    console.log(+add(7)(0));                 // 7
    console.log(+add(0));                    // 0
    
    0 讨论(0)
提交回复
热议问题