Arguments Optional - Short and Works, but Good Practice?

Arguments Optional - Short and Works, but Good Practice?
0.0 0

#1

Hey, after a fair bit of confused wandering I came up with a solution to this that is only a few lines…
I looked up some other answers and they seemed a bit longer and didn’t look to clear.

I’d appreciate any input on whether this was clean or if I lost sight of something and it just happens to work:

function addTogether() {
  
  function makeAdder(x) {  // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
    return function(y) {
      if(typeof y === "number") return x + y;
    };
  }
  
  if(typeof arguments[0] === "number" &&
     typeof arguments[arguments.length-1] === "number") {
    var addFirst = makeAdder(arguments[0]);
    var addSecond = arguments.length === 2 ? addFirst(arguments[1]) : addFirst;

    return addSecond;
  }
}

addTogether(2)(3); // returns 5
addTogether(2)([3]); // returns undefined

#2

I organized my code a little differently but took the same basic approach

function addTogether() {
  var first = arguments[0];
  
  if (arguments.length == 1 && typeof first === "number"){
    return function(x){
      return addTogether(first, x);
    };
  }
  
  if (arguments.length == 2 && typeof first === "number" && typeof arguments[1] === "number"){
    return first + arguments[1];
  }
}

#4

Both of your replies help me wrap my head around what I’m actually trying to achieve here. They’re very clear. Thanks.

I thought there was some issue when I was trying to use those ES6 things earlier but now I see you can put the warnings in check. Just wondering though, is there some issue using ES6 features or do you use it less now for some reason(s)?