Skip to content

Instantly share code, notes, and snippets.

@JeffOgah
Created February 21, 2019 00:07
Show Gist options
  • Select an option

  • Save JeffOgah/962acb678269929f8376c0401997c89b to your computer and use it in GitHub Desktop.

Select an option

Save JeffOgah/962acb678269929f8376c0401997c89b to your computer and use it in GitHub Desktop.
JavaScript Intermediate Algorithm Scripting: Arguments Optional
/*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.
*/
function addTogether() {
let firstNum, secondNum; //numbers to be added
//function to check if argument is a number
function validNumber(num) {
if (typeof num == 'number')
{
return num;
}
return undefined;
}
//if 2 or more arguments are passed
//check first two arguments, sum if both are numbers else return undefined
if (arguments.length >1) {
firstNum = validNumber(arguments[0]);
secondNum = validNumber(arguments[1]);
return (firstNum && secondNum ? firstNum + secondNum : undefined);
}
else {
firstNum = validNumber(arguments[0]);
//check if any undefined number was passed, return function to accept
//return a function to accept and check second number if present then sum
if (firstNum !== undefined) {
return function secondNumber(arg){
secondNum = validNumber(arg);
if (firstNum === undefined || secondNum === undefined ) {
return undefined;
}
else {return firstNum + secondNum;}
}
}
}
}
addTogether(2,3); //returns 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment