I am currently trying to solve Arguments Optional intermediate algorithm. I seem to pass the following requirements.
-
addTogether(2, 3)
should return 5.
-
addTogether("http://bit.ly/IqT6zt")
should return undefined.
-
addTogether(2, "3")
should return undefined.
And these two do not pass.
-
addTogether(2)(3)
should return 5.
-
addTogether(2)([3])
should return undefined.
function addTogether() {
let answer;
let myArgs = [].slice.call(arguments);
let val1 = arguments[0];
let val2 = arguments[1];
if(typeof val1 === 'number'&& typeof val2 === 'number'){
answer = val1 + val2;
}else if(myArgs[val1] === 2){
answer += val1[0] + val1[1]
}
return answer
}
addTogether(2,3);
Thank you in advance for any help with this issue.
This is a tricky thing for many people to wrap their heads around for the first time, but what you need to do for those test cases is a function.
When addTogether()
is called with only one parameter, it should return a function definition that expects only one parameter and returns the sum of that new parameter and the original parameter that addTogether()
was called with.
I finally got all requirements to pass. Had to rewrite my code as follows.
function addTogether() {
let answer;
let arr = [].slice.call(arguments);
let test = arr.every(el => typeof el === 'number');//Test if argument passes being a number test by looping arguments and testing each one.
if(test){//If test is passed add arguments together.
answer = arr[0] + arr[1];
}
if(arr.length < 2){//If only one argument is found example (2) of (2)(3) then run addMe function.
if(test){
let addMe;
addMe = (num2) => {
if(typeof num2 === 'number'){//If num2 is a number then add first argument arr[0] with num2 which is 3.
return arr[0] + num2
}
}
answer = addMe;
}
}
return answer;
}
addTogether(2,3);
Hope i explained how i was trying to solve algorithm. Thank you ArielLeslie