Variadic curried sum function

前端 未结 16 1849
清酒与你
清酒与你 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:27

    This is an example of using empty brackets in the last call as a close key (from my last interview):

    sum(1)(4)(66)(35)(3)()

    function sum(numberOne) {
      var count = numberOne;
      return function by(numberTwo) {
        if (numberTwo === undefined) {
          return count;
        } else {
          count += numberTwo;
          return by;
        }
      }
    }
    console.log(sum(1)(4)(66)(35)(3)());

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

    Here's a more generic solution that would work for non-unary params as well:

    const sum = function (...args) {
      let total = args.reduce((acc, arg) => acc+arg, 0)
      function add (...args2) {
        if (args2.length) {
          total = args2.reduce((acc, arg) => acc+arg, total)
          return add
        }
        return total
      }
    
      return add
    }
    
    document.write( sum(1)(2)() , '<br/>') // with unary params
    document.write( sum(1,2)() , '<br/>') // with binary params
    document.write( sum(1)(2)(3)() , '<br/>') // with unary params
    document.write( sum(1)(2,3)() , '<br/>') // with binary params
    document.write( sum(1)(2)(3)(4)() , '<br/>') // with unary params
    document.write( sum(1)(2,3,4)() , '<br/>') // with ternary params

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

    To make sum(1) callable as sum(1)(2), it must return a function.

    The function can be either called or converted to a number with valueOf.

    function sum(a) {
    
       var sum = a;
       function f(b) {
           sum += b;
           return f;
        }
       f.toString = function() { return sum }
       return f
    }
    
    0 讨论(0)
  • 2020-11-22 07:34

    Try this

    function sum (...args) {
      return Object.assign(
        sum.bind(null, ...args),
        { valueOf: () => args.reduce((a, c) => a + c, 0) }
      )
    }
    
    console.log(+sum(1)(2)(3,2,1)(16))
    

    Here you can see a medium post about carried functions with unlimited arguments

    https://medium.com/@seenarowhani95/infinite-currying-in-javascript-38400827e581

    0 讨论(0)
提交回复
热议问题