0

I am doing an exercise for freecodecamp where I have to create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.

For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.

My code is as follow:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function isFunction(functionToCheck) {
 var getType = {};
 return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}

function addTogether() {
  var args = Array.prototype.slice.call(arguments);
  var param1=args[0];

  var sum=function(){
    var argSub=Array.prototype.slice.call(arguments);
    var param2=argSub[0];
    if (isNumber(param2))
       return;
    else
      return param1+param2;
  };

  if (args.length===1){
    return sum;
  } else if (isNumber(param1)){
    return param1+args[1];
  }
}

addTogether(2,3);

When I do addTogether (2)(3) should return 5, and when I execute addTogether (2,"3") should return 'undefined'.

I think I am failing in the way I am checking the params. I have tried many diferents configuration and I am stuck. Any advice??

Thanks

myhappycoding
  • 648
  • 7
  • 20

1 Answers1

-1

Use of closure to add numbers. Few lines are commented to give idea how inner function is getting called. Ref : closure and IIFE in Javascript.

function sum(x) {
  var input = x;

  function add(y) {
    return input + y;
  }
  return add;
}
//var sum1 = sum(2);
//console.log(sum1(3)); // 5
console.log(sum(2)(3)); //5
crazyvraj
  • 37
  • 5