0

I'm pretty baffled by this question that I came across for my interview prep. It wants me to be able to write a function called multiply that takes in parameters in this haphazard way:

multiply(5)(6);

I tried to write a callback and then refer to this in the return statement, but it was not kosher.

function multiply(function(value){
return this * value;
});
}

Does this problem require recursion?

Thanks!

Jon
  • 61
  • 5

1 Answers1

2

If you want to call your function in this multiply(5)(6); way,

Then you must be searching for function currying. And that can be accomplished by,

function multiply(a){
 return function(b){
   return b * a;
 }
} 

//your way
console.log(multiply(2)(2)) //4

//The standard way
var multiplyBy5 = multiply(5);
var res = multiplyBy5(3); 
console.log(res); // 15;

var multiplyBy10 = multiply(10);
var res = multiplyBy5(3);
console.log(res); // 30;
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130