Variadic curried sum function

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

    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)() , '
    ') // with unary params document.write( sum(1,2)() , '
    ') // with binary params document.write( sum(1)(2)(3)() , '
    ') // with unary params document.write( sum(1)(2,3)() , '
    ') // with binary params document.write( sum(1)(2)(3)(4)() , '
    ') // with unary params document.write( sum(1)(2,3,4)() , '
    ') // with ternary params

提交回复
热议问题