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