Skip to content

Instantly share code, notes, and snippets.

@martin-mok
Created January 13, 2020 19:16
Show Gist options
  • Select an option

  • Save martin-mok/00ddd151333836ff203d26d0976d7e6e to your computer and use it in GitHub Desktop.

Select an option

Save martin-mok/00ddd151333836ff203d26d0976d7e6e to your computer and use it in GitHub Desktop.
freecodecamp: Arguments Optional

Description

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.

Tests

tests:
  - text: <code>addTogether(2, 3)</code> should return 5.
    testString: assert.deepEqual(addTogether(2, 3), 5);
  - text: <code>addTogether(2)(3)</code> should return 5.
    testString: assert.deepEqual(addTogether(2)(3), 5);
  - text: <code>addTogether("http://bit.ly/IqT6zt")</code> should return undefined.
    testString: assert.isUndefined(addTogether("http://bit.ly/IqT6zt"));
  - text: <code>addTogether(2, "3")</code> should return undefined.
    testString: assert.isUndefined(addTogether(2, "3"));
  - text: <code>addTogether(2)([3])</code> should return undefined.
    testString: assert.isUndefined(addTogether(2)([3]));

Solution

My soln:

function addTogether() {
  for(let i=0;i<arguments.length;i++){
    if(typeof arguments[i] !=="number"){
      return undefined;
    }
  }
  if(arguments.length===1){
    let b=arguments[0];

    if(typeof b !=="number"){
      return undefined;
    }
    
    return function(a){
      if(typeof a !=="number"){
      return undefined;
    }
      return a+b;
      };
  } else {
    return arguments[0]+arguments[1];
  }
}

addTogether(2,3);

Tidy up:

function addTogether() {
  var a = arguments[0];
  var b = arguments[1];
  if (typeof a === 'number'&& typeof b === 'number'){
    return a+b;
  }
  else if (arguments.length===1&&typeof a === 'number'){
    return function(c){
      if (typeof c === 'number'){
        return a+c;
      }
    };
  }
  else{return undefined;}
}

recursive solution:

function addTogether() {
  const [a, b] = arguments;

  if (typeof a !== 'number' || (b && typeof b !== 'number')) {
    return undefined;
  }

  if (b) {
    return a + b;
  }

  return c => addTogether(a, c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment