Problem: 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.
Solution should return:
addTogether(2, 3) should return 5. addTogether(2)(3) should return 5. addTogether(2, "3") should return undefined. addTogether(2)([3]) should return undefined.
I tried everything I could, but the only thing that worked, and is purportedly the best solution so far is the following:
function addTogether() {
"use strict";
// check if argument(s) valid number
var validateNum = function(num) {
if(typeof num !== 'number') {
return undefined;
} else
return num;
};
// is there is one argument or two
if(arguments.length > 1) {
var a = validateNum(arguments[0]);
var b = validateNum(arguments[1]);
if(a === undefined || b === undefined) {
return undefined;
} else {
return a + b;
}
// if only one argument, return function that expects one argument and returns sum.
} else {
var c = arguments[0];
// start here
if(validateNum(c)) {
return function(arg2) {
if(c === undefined || validateNum(arg2) === undefined) {
return undefined;
} else {
return c + arg2;
}
}; // belongs to return function(arg2) {}
}
}
}
addTogether(2)(3);