I am running into an error: Uncaught TypeError TypeError: multipliers.reduce(...) is not a function
. I was looking at currying and partial application. I expected multiply
function to correctly invoke through an array of multipliers. Can someone please explain what I’m missing in my multiply
function?
multiply function that multiplies integers, but in a special way.
The function’s output can be invoked repeatedly until you call it with no arguments.
For example, multiply(3)(4)(5)()
should return 3 * 4 * 5 = 60
.
I am using a helper function solution(multipliers)
that takes all the multipliers and then passes them to multiply
as described above.
Input
multipliers: [3, 4, 5]
Output
60
Code
function multiply(x) {
return function(y) { // anonymous function
return function(z) { // anonymous function
return x * y + z;
}
}
}
// this function lets you invoke something like multiply(3)(4)(5)() with dynamic arguments
function solution(multipliers) {
return (multipliers.reduce((prev, arg) => {
if (prev) {
return prev(arg);
}
return multiply(arg);
}, null))();
}
console.log(solution([3, 4, 5]));
3
Answers
You have to push all parameters to an array before calling an array method on it. Or else you can use the arguments parameters inside the function to get all the parameters.
Can you share how the function has been called?
Use the
multiply
function as the initial value for thereduce
call, and drop the final()
:Your
multiply
function is defined incorrectly. If you wantmultiply(3)(4)(5)()
to evaluate to60
then you need to define themultiply
function as follows.Once you define
multiply
correctly, you can definesolution
as follows.