-1

sum(2)(3)(4)....(n)

find the sum of n number of paranthas supplied with number as a arguments

I have tried

function sum (a){
    return function (b){
        return (a+b)
    }
}

1 Answers1

0

( I have to jet, will add explanation in a bit). But in a nutshell:

  • As long as you have arguments you return a function that's keeping within it the sum and keeps adding each argument. I cheat and override toString of function to output the current value of sum.
  • The fast way at the moment that I could think of not needing that toString is to just execute the function with an empty parameter and then not return a function but rather the sum value.

The bad thing? Well, overriding the toString you'll see in the console.log() might confuse users, since the actual type of what's returned is a function and not a number.

var string_sum = sum(1)(1)(1);
console.log( string_sum + "  of type " + typeof(string_sum) );
var num_sum = sum(1)(1)(1)(1)(1)(1)();
console.log( num_sum + " of type " + typeof(num_sum) );

function sum(x) {
  var sum = x;

  var sum_closure = function s(y){
     if ( y != undefined ){
      sum += y;
      return s;
     } else
      return sum;
  };
    
  if( ! Number.isInteger(sum_closure) )  
    Object.defineProperty(sum_closure, 'toString', {
          value: function () {
              return sum;
          }
      });
  
  return sum_closure;
}
Chayemor
  • 3,577
  • 4
  • 31
  • 54
  • check this i have got the solution let add = (a) => { let sum = a; funct = function(b) { sum += b; return funct; }; Object.defineProperty(funct, 'valueOf', { value: function() { return sum; } }); return funct; }; console.log(+add(1)(2)(3)) – vishal kumar May 22 '18 at 05:45