Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:55
Show Gist options
  • Save rfprod/cf53ba0e2ea4f2e4affc to your computer and use it in GitHub Desktop.
Save rfprod/cf53ba0e2ea4f2e4affc to your computer and use it in GitHub Desktop.
Optional Arguments
var sum = 0;
var undefinedCounter = 0;
function add() {
var argsArr = [];
for (var i=0;i<arguments.length;i++){
argsArr.push(arguments[i]);
}
filterValueType(argsArr);
if (argsArr.length < 2 && undefinedCounter < 1){
sum = argsArr[0];
return function(n){
sum = sum + arguments[0];
filterValueType(arguments);
if (undefinedCounter > 0){
return undefined;
}else{
return sum;
}
};
}else{
sum = argsArr[0] + argsArr[1];
if (undefinedCounter > 0){
return undefined;
}else{
return sum;
}
}
function filterValueType(arrArgs){
undefinedCounter = 0;
for (var j=0;j<arrArgs.length;j++){
if (typeof arrArgs[j] === 'string' || isArray(arrArgs[j]) || isNaN(arrArgs[j])){
undefinedCounter = undefinedCounter + 1;
}
}
return undefinedCounter;
}
function isArray(inputArr) {
return inputArr.constructor.toString().indexOf("Array") > -1;
}
}
add(2, 3);
// more example calls
// add(2, "3");
// add("http://bit.ly/IqT6zt");
// add(2)(3);
// add(2)([3]);

Optional Arguments

A function that sums two arguments together. If only one argument is provided, it returns a function that expects one argument and returns the sum. For example, add(2, 3) should return 5, while add(2) should return a function. Calling this returned function with a single argument will then return the sum. If either argument isn't a valid number, returns undefined.

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment