Okay, another challenge thats eating me alive:
function addTogether() {
var checkNum = function(num) {
if (typeof num === "number") {
return num;
} else
return undefined;
};
var a = checkNum(arguments[0]);
var b = checkNum(arguments[1]);
if (arguments.length > 1) {
if (typeof a === "number" && typeof b === "number") {
return a + b ;
} else {
return undefined;
}
} else {
if (checkNum(a)) {
return function(arg2) {
if (a === undefined || checkNum(arg2) === undefined) {
return undefined;
} else {
return a + arg2;
}
};
}
}
}
addTogether(2,3);
EXPECTED OUTPUS:
addTogether(2, 3) should return 5.
addTogether(2)(3) should return 5.
addTogether("http://bit.ly/IqT6zt") should return undefined.
addTogether(2, "3") should return undefined.
addTogether(2)([3]) should return undefined.
Everything is clear and shinny, until that part with “arg2” How exactly is arg2 defined? arg2 is just …something that does not yet exist… I know these are called closures, but i havent had a challenge explaining that to me, and i did some research on MDN but there isnt a single case explaining how something that is not defined, can somehow get recognized as defined…
So the trick here is that your return value can be a function. That’s the way that you handle the case of addTogether(2)(3) should return 5
. Here’s what needs to happen: addTogether(2)
needs to return a function. 3
will then become the argument that your returned function receives.
how about I have addTogether(2)(3)(4)
and i return a function, will it return 3? and if i return another function after that, will it return 4?
dumb question maybe, but im just curious
The scope of this challenge is to only add two numbers, so addTogether(2)(3)
would return 5
and addTogether(2)(3)(4)
would probably give you the error “5 is not a function”.
But if you want extra credit (of the imaginary sort), then you could write a function that is flexible enough to handle an unknown amount of chaining.
I was experimenting with something like this:
function addTogether() {
var checkNum = function(num) {
if (typeof num === "number") {
return num;
} else
return undefined;
};
var a = checkNum(arguments[0]);
var b = checkNum(arguments[1]);
var c = checkNum(arguments[2]);
if (arguments.length > 1) {
if (typeof a === "number" && typeof b === "number" && typeof c === "number") {
return a + b + c;
} else {
return undefined;
}
} else {
if (checkNum(a)) {
return function(arg2, arg3) {
if (a === undefined || checkNum(arg2) === undefined || checkNum(arg3) === undefined) {
return undefined;
} else {
return a + arg2 + arg3;
}
};
}
}
}
addTogether(2)(3)(4);
unfortunately it doesnt work
I really should have included the caveat that I have not done this in a way that would accept arbitrary chaining and I don’t know how much it would rely on some advanced techniques that you probably haven’t heard of.
For now, I’d focus on the actual challenge requirement of 2 values.
1 Like