Variadic curried sum function

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

提交回复
热议问题