skip to Main Content

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


  1. 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?

    Login or Signup to reply.
  2. Use the multiply function as the initial value for the reduce call, and drop the final ():

    function solution(multipliers) {
        return multipliers.reduce((prev, arg) => prev(arg), multiply);
    }
    console.log(solution([3, 4, 5]));
    
    function multiply(x) {
        return function(y) {
            return function(z) {
                return x * y + z;
            }
        }
    }
    Login or Signup to reply.
  3. Your multiply function is defined incorrectly. If you want multiply(3)(4)(5)() to evaluate to 60 then you need to define the multiply function as follows.

    // x is required, y is optional, both are numbers
    const getMultiply = (x) => (y) =>
      typeof y === "undefined" ? x : getMultiply(x * y);
    
    // 1 is the identity element of multiplication
    const multiply = getMultiply(1);
    
    console.log(multiply(3)(4)(5)()); // 60

    Once you define multiply correctly, you can define solution as follows.

    // x is required, y is optional, both are numbers
    const getMultiply = (x) => (y) =>
      typeof y === "undefined" ? x : getMultiply(x * y);
    
    // 1 is the identity element of multiplication
    const multiply = getMultiply(1);
    
    const solution = (multipliers) =>
      multipliers.reduce((f, x) => f(x), multiply)();
    
    console.log(solution([3, 4, 5])); // 60
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search