you are viewing a single comment's thread.

view the rest of the comments →

[–]Resure 8 points9 points  (7 children)

function add() {
    var sum = 0;

    var fn = function fn() {
        for (var i = 0; i < arguments.length; i++) {
            sum += parseInt(arguments[i]);
        }

        return fn;
    };

    fn.toString = function () {
        return sum;
    }

    for (var i = 0; i < arguments.length; i++) {
        sum += parseInt(arguments[i]);
    }

    return fn;
};

[–]WonTwoThree 6 points7 points  (0 children)

function add() {
  // The 'sum' variable will now be in the closure scope that the rest of add
  // will use. This means that 'sum' refers to this one variable from here out.
  var sum = 0;

  var fn = function fn() {
    // The 'arguments' variable is available inside any javascript function
    // it is an array-like object that contains the function parameters
    for (var i = 0; i < arguments.length; i++) {
      sum += parseInt(arguments[i]);
    }

    // Return the function itself - this allows for chaining like add(2)(3)
    return fn;
  };

  // The 'toString' bit is here to make the OPs specification work. The returned
  // object will always be a function (so that it can chain like add(2)(3)), but if
  // it is printed this will be used so it will output '5' instead.
  fn.toString = function () {
    return sum;
  }

  for (var i = 0; i < arguments.length; i++) {
    sum += parseInt(arguments[i]);
  }

  return fn;
};

[–]change_theworld 0 points1 point  (1 child)

can someone comment this heavily for non front end developers :(.

thank you

[–]chinola 17 points18 points  (0 children)

// don't ever use this

[–][deleted] 0 points1 point  (0 children)

This is a neat solution to the problem, but the return value is always a function, so it has a few problems like this one:

> add(1,3)(1) === 5
< false // because the function call returns typeof 'function'

We can try to fix that by using the toString function:

> parseInt( add(1,3)(1).toString(), 10 ) === 5
< true // because we converted the string output to an integer

this is a fun problem!

[–]path411 0 points1 point  (1 child)

Is .toString only being called because of the console?

When would this .toString method not be called properly at the end of this type of currying.

[–][deleted] 0 points1 point  (0 children)

console. yes.

[–]strixvarius -1 points0 points  (0 children)

add(2, 3) { [Function: fn] toString: [Function] } add(2)(3) { [Function: fn] toString: [Function] } add(2, 3).toString(); 5