A problem that may be presented to you in a programming interview may be something like ... presented this:
JavaScript
console.log(mul(2)(3)(4)); // 24
... how would you create a function that would enable this calculation to work properly?
If you're unfamiliar with combinators or curried functions, this may look strange to you. Normally, you see functions called with multiple parameters like this:
JavaScript
console.log(mul(2,3,4));
As strange as it may look, it can be solved by returning anonymous, nested functions giving us access to the each and all of the passed parameters.
Hey, Tyler here. I'm currently working on some great web development and digital marketing products and services over at ZeroToDigital.
If that sounds interesting to you, please check it out!
In this post, I'm going to show you how to create a curried function that will allow our provided multiplication function to work properly.
If you'd rather see this post in video format, watch the video below and be sure to subscribe to my YouTube playlist Tyler Answers Interview Questions.
The JavaScript solution to function combinators can be very concise.
In the answer below, we've created a function called mul that receives 3 individual integer parameters and returns the product of their multiplication.
JavaScript
const mul = x => {
return y => {
return z => {
return x * y * z
}
}
}
const mul1 = x => y => z => x * y * z
mul(2)(3)(4) // 24
mul(4)(3)(4) // 48
As of v7, the PHP solution to this is very concise as well. The only difference is that arguments are not automatically passed in PHP. they need to be passed via the use keyword.
PHP
function mul($x) {
return function($y) use ($x) {
return function($z) use ($x, $y) {
return $x * $y * $z;
};
};
};
echo mul(2)(3)(4); // 24
echo mul(4)(3)(4); // 48