Javascript function that accepts a parameter in a different format
I was recently asked to write a javascript function (this was a coding test) where they wanted me to implement a function that will add and return values.
add(3,2);//should return 5
add(3)(2); //should return 5
I'm not sure if this is possible at all. I am not an expert in javascript, so it is possible to get the key from google search.
+3
source to share
2 answers
You will need to check if the first argument was specified first; if so, return the result immediately; otherwise, return the function that completes the addition:
function add(a, b)
{
if (typeof b == 'undefined') {
return function(b) {
return a + b;
}
} else {
return a + b;
}
}
Alternatively, if you don't like duplicate logic:
function add(a, b)
{
var f = function(b) {
return a + b;
};
return typeof b == 'undefined' ? f : f(b);
}
It is also called partial function application or currying.
+5
source to share