Search code examples
javascriptmultiplicationcurryingpartial-application

js function repeatedly invokes through an array of multipliers


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]));

Solution

  • I was able to modify only the multiply function using currying thanks to @ghassen-louhaichi's link to a related question: Create a function with an undetermined number of successive calls.

    function multiply(x) {
        return function() {
            if (arguments.length == 0) {
                return x;
            } else {
                return multiply(x * arguments[0]);
            }
        }
    }
    
    // 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]));

    The first call to multiply, returns the inner function. depending on the number of arguments passed to the inner function, it returns the value of multiply's argument as it is or it calls again ´multiply´ with the updated running total (thus returning again the inner function to be called again).

    The limitation (of this implementation) is that you HAVE TO make a final call with no arguments to have to final value.