Sum function work with recursion and multiple arguments

Viewed 1727

Is there a away to create a sum function that works with both recursive call (e.g (1)(2)(3)(4)), and multiple arguments (e.g (1, 2, 3, 4))?

Like this:

sum(5, 5) // 10
sum(5)(5) // 10

Thank you.

3 Answers

Reference: https://codeburst.io/perpetual-currying-in-javascript-5ae1c749adc5

Thanks to Param Singh, Who came up with a good solution for infinite variadic currying problem

            function callFun(fn){

                const doTo = (args) => args.reduce((acc, a) => fn.call(fn, acc, a))

                const next =(...args)=>{
                    return (...innerArg)=> {
                        if(innerArg.length){
                            return next(...args, doTo(innerArg))
                        }else{
                            return doTo(args)
                        }
                    }
                }

                return next()    
            }

            const sum = callFun((a,b) => a + b)

            console.log(sum(1)(2)(3,2,1)())
Related