Mir Stephen
Mir Stephen

Reputation: 1927

Arguments Optional

Currently I am working on a freeCodeCamp challenge. I would rather copy/paste the challenge itself than writing it myself.

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.

Calling this returned function with a single argument will then return the sum:

var sumTwoAnd = addTogether(2);

sumTwoAnd(3) returns 5.

If either argument isn't a valid number, return undefined.

this is the solution, I created:

function addTogether(a) {
  for (let j = 0; j < arguments.length; j++){
    // console.log(typeof(arguments[j]));
    if(typeof(arguments[j]) != "number"){
      return undefined;
    } else if (typeof(arguments[j]) == 'string') {
      return undefined;
    } else {
      console.log('go up');
      if (arguments.length >= 2){
        let sum = 0;
        for(let i = 0; i < arguments.length; i++){
          sum += arguments[i];
        }
        return sum;
      }
    }
  }

  return function(b){
    if (typeof(b) == 'object'){
      return undefined;
    } else {
      return a + b;
    }
  }
}

This solution is 80% correct, but it can't deal with addTogether(2, "3") should return undefined. although I added this check typeof(arguments[j]) == 'string'. How do I make it work? Thank you.

Upvotes: 0

Views: 256

Answers (4)

Mouafa
Mouafa

Reputation: 29

Function bind could be used to reduce the duplicated code as follow:

function addTogether(a, b) {
  if (Number.isNaN(b)) return addTogether.bind(null, a)
  return a + b
 }

Upvotes: 0

Wayne
Wayne

Reputation: 39

Can you provided more details about your test case?

function addTogether(a) {
  const argLength = arguments.length;
  if(argLength >= 2) {
    let sum = 0;
    for(let i = 0; i < argLength; i++) {
      if(typeof arguments[i] === 'number') {
        sum += arguments[i];
      } else {
        return undefined;
      }
    }
    return sum;
  } else {
    return function(b) {
      if(typeof a !== 'number') {
        return undefined;
      }
      if(typeof b === 'number') {
        return a + b;
      }
    }
  }
}

Upvotes: 0

User863
User863

Reputation: 20039

Try calling addTogether()

function addTogether(a, b) {
  if(typeof(a) !== 'number' || (b != undefined && typeof(b) !== 'number')) {
    return undefined;
  }
  if(b == undefined) {
    return c => addTogether(a, c);
  }
  return a + b;
}

addTogether(2,3);

Upvotes: 1

Mohamed Belhaj
Mohamed Belhaj

Reputation: 81

function addTogether(a, b = null) {
   if (b === undefined || typeof(b) !== 'number') return a + b;
   return function (c) {
     return a + c
   }
 }

Upvotes: 1

Related Questions