Variadic curried sum function

前端 未结 16 2002
清酒与你
清酒与你 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: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)();
    

提交回复
热议问题