Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 = ad…
function addTogether() {
//create a function that test whether arguments are numbers
//if not a number return undefined, if it is return the number
function checkArgs(val){
if(typeof val !== 'number'){
return undefined;
}
return val;
}
//check the first argument is a number and store the result in a variable
var x = checkArgs(arguments[0]);
//if there are two arguments provided
//check the second argument is a number and store the result in a variable
if(arguments.length > 1){
var y = checkArgs(arguments[1]);
//check that both arguments are numbers (not undefined) and do the sum
if(x && y){
return x + y;
}
else{
return undefined;
}
}
//if there's only one argument, provided it is a number return a function
//to add a second number, checking first that it is a number.
else{
if(x){
return function(y){
if(checkArgs(y)){
return x + y;
}
};
}
}
}
addTogether(2,3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.