1
A friend of mine challenged me to write a function that works with both of these scenarios
add(1,2) // 3
add(1)(2) // 3
My instinct was the write an add() function that returns itself but I'm not sure I'm heading in the right direction. This failed.
function add(num1, num2){
if (num1 && num2){
return num1 + num2;
} else {
return this;
}
}
alert(add(1)(2));
So I started reading up on functions that return other functions or return themselves.
http://davidwalsh.name/javascript-functions https://stackoverflow.com/questions/17235259/javascript-self-calling-function-returns-a-closure-what-is-it-for https://stackoverflow.com/questions/17235259/javascript-self-calling-function-returns-a-closure-what-is-it-for
I am going to keep trying, but if someone out there has a slick solution, I'd love to see it!
Welcome to PPCG! You tagged this as code-golf, meaning that the shortest possible code will win the contest. If this is your intention, you should remove the code-challenge tag. – Dennis – 2015-07-09T01:09:33.070
I have an answer here on stackoverflow
– Patrick Roberts – 2015-07-09T03:52:13.653FYI this is called currying. – gcampbell – 2016-06-10T10:34:03.970