Arguments Optional
33-ий день программы "#100 Days Of Code"
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.
function addTogether() {
var results;
if(arguments.length <=3){
var a1 = arguments[0];
var a2 = arguments[1];
if(typeof(a2)==='number'){
if(typeof(a1) ==='number'){
results = a1 +a2;
}
} else if(a2===undefined && typeof(a1)==='number'){
return function(a2){
if(typeof(a2)==='number'){
return a1 + a2;
}
else return results;
};
}
}
return results;
}
addTogether(2,3);
Ответы:
addTogether(2, 3)
return 5.
addTogether(2)(3)
return 5.
addTogether("http://bit.ly/IqT6zt")
return undefined.
addTogether(2, "3")
return undefined.
addTogether(2)([3])
return undefined.
Комментариев нет:
Отправить комментарий