Skip to content

Instantly share code, notes, and snippets.

@elisavetTriant
Created July 18, 2019 06:55
Show Gist options
  • Save elisavetTriant/ab32fadfb0264f8a1a85b9cc353ad40a to your computer and use it in GitHub Desktop.
Save elisavetTriant/ab32fadfb0264f8a1a85b9cc353ad40a to your computer and use it in GitHub Desktop.
/*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.
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.
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator*/
function addTogether() {
let args = [];
for (let i=0; i< arguments.length; i++){
args[i] = arguments[i];
}
//if we have two (or more) arguments, add first two, if both numbers, else return undefined. Else return a function, if both nums, else undefined
if (args.length > 1) {
return (typeof args[0] === 'number' && typeof args[1] === 'number' ? args[0] + args[1] : undefined);
} else if (args.length === 1) {
return (typeof args[0] === 'number' ?
function(num) {
return (typeof num === 'number' ? args[0] + num : undefined);
}
: undefined)
}
}
addTogether(2,3);
/*
addTogether(2, 3) should return 5.
Passed
addTogether(2)(3) should return 5.
Passed
addTogether("http://bit.ly/IqT6zt") should return undefined.
Passed
addTogether(2, "3") should return undefined.
Passed
addTogether(2)([3]) should return undefined.
Passed
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment