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.