Variadic curried sum function

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

    I'm posting this revision as its own post since I apparently don't have enough reputation yet to just leave it as a comment. This is a revision of @Rafael 's excellent solution.

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

    I didn't see a reason to keep the v.toString bit, as it didn't seem necessary. If I erred in doing so, please let me know in the comments why v.toString is required (it passed my tests fine without it). Converted the rest of the anonymous functions to arrow functions for ease of reading.

提交回复
热议问题