Can Anybody help me to write this function Write a function where the output for both “sum(2,3)” and “sum(2)(3)” will be 5
I think we need to write function using closer!
Can Anybody help me to write this function Write a function where the output for both “sum(2,3)” and “sum(2)(3)” will be 5
I think we need to write function using closer!
Syntax as follows: sum(2)(3)
is related with currying. It means that you need to return another function inside the main function to get the desired result.
Here's a nice video about currying on Youtube, from which I've learned a lot.
function sum(a){
if (arguments.length == 1) {
return function(b){
return a + b;
}
} else {
return Object.keys(arguments).reduce((a,b) => arguments[a] + arguments[b]);
}
}
console.log(sum(2,3));
console.log(sum(2)(3));
As Karl-André Gagnon proposed, it can be also done with bind
function.
function sum(a){
if (arguments.length == 1) {
return sum.bind(this, a)
} else {
return Object.keys(arguments).reduce((a,b) => arguments[a] + arguments[b]);
}
}
console.log(sum(2,3));
console.log(sum(2)(3));