2

Someone ask me an question to write an closure function which should return the sum of input provided and input can be one argument upto n. so user can call
sum(5) OR sum(4)(3) OR sum(1)(2)...(n), I wrote the below function using recursion but facing an issue where I need to add an empty parentheses at the end for the below function to work,

 function sum(x) {

        return function (y) {
            if (y) {
                return sum(x + y);
            }
            else {
                return x;
            }

        }
    }
     // this result in 12 as I am using an empty parentheses at the end
    console.log(sum(5)(6)(1)());

  // below two will return output as [Function]
    console.log(sum(5)(6)(1)(5)(6)(1));
    console.log(sum(5));

is there any better way to implement this?

Akash
  • 848
  • 1
  • 11
  • 30
  • 1
    It's not possible - eg, from the expression `sum(5)`, how is the interpreter to know that the result should be a number value, rather than a function that can be invoked again with `(6)`? Either do it like you're doing, and invoke the function again, or put a `valueOf` or `toString` method on the returned function, and coerce it to a string – CertainPerformance Jan 20 '20 at 23:55
  • I hope this is just for experimentation or learning, rather than productional code. – Taplar Jan 20 '20 at 23:57
  • @Taplar this is an interview question recently asked. so yes, it is more of a learning rather than productional code – Akash Jan 20 '20 at 23:59

0 Answers0