1

I have this function that need to have the ability to take in multiple sets of inputs and return the sum of every input. For example:

magicFunction(1)(2)(3) => 6

I accomplished this with the code below. 'f(y)' will run until there are no input sets left.

function magicFunction(x) {
  var sum = x;  

  function f(y) { 
    sum += y;
    return f;
  };  
  return f;
}

My issue is I want the function to return the sum, but this function will return '[Function: f]' at the end. So currently, the function does this:

magicFunction(1)(2)(3) => [Function: f]

I can't figure out how to return the sum after the last input. Is there a way I can check if the code reached the last input set? So instead of 'return f', I can run 'return sum'.

I thought about adding a 'toString' method and then use 'console.log' to output the result. But i'm looking for the function to return the value, not just output the value onto the console.

davidhu
  • 9,523
  • 6
  • 32
  • 53

2 Answers2

5

You could implement a toString method or a valueOf method.

function magicFunction(x) {
    var sum = x;  

    function f(y) { 
        sum += y;
        return f;
    }; 
    f.toString = function () { return sum; };      // for expecting string, 1st log
    f.valueOf = function () { return 100 + sum; }; // for expecting numbers, 2nd log

    return f;
}

console.log(magicFunction(2)(3)(4));
console.log(magicFunction(2)(3) + magicFunction(4)(5));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I thought about that, but I'm looking for the function to return a value, not just to log it to the console. – davidhu Jul 06 '16 at 16:05
  • The function *is* returning a value. She is simply logging that returned value to the console. – Gerardo Furtado Jul 06 '16 at 16:08
  • If you replaced `toString` with `valueOf`, there wouldn’t be a difference. You could write `var myVar = magicFunction(2)(3)(4) + 11;` and get `20`. Otherwise you’d need to add zero to explicitly get the end result. I’m not aware of any way to make this possible with the original syntax in the question in JavaScript. – Sebastian Simon Jul 06 '16 at 16:14
  • 1
    @davidhu2000 You can simply do `+magicFunction(3)(2)(7)(9)` to get the value of function called. – Morteza Tourani Jul 07 '16 at 00:27
3

You could change your function f to

function f(y) { 
    if(!y) {
        return sum;
    }
    sum += y;
    return f;
}

and then, calling the magicFunction with an empty parameter at last: magicFunction(1)(4)(7)();

Gaunt
  • 649
  • 8
  • 20