mul(a)(b)(c)

Easy Important

Prompt

Write a JavaScript function called mul that implements multiplication of three numbers using currying. The function should take three parameters, a, b, and c, and return their product.

mul(1)(2)(3); // Returns 6
mul(5)(5)(5); // Returns 125

Playground

Hint

Start by defining a function that takes a single parameter. This forms the basis for currying. Gradually extend this function to accept additional parameters using nested function definitions.

Hint

Currying involves breaking down a function that takes multiple arguments into a sequence of functions, each taking a single argument. Think about how you can compose these functions together to achieve the desired result. Start by returning functions from within functions until you reach the desired level of nesting.

Solution #1

Solution #2

Explanation

This solution utilizes a concept called currying to create a function that multiplies three numbers together.

  • The mul function takes a single parameter a.
  • Inside mul, another function is returned. This inner function takes a single parameter b.
  • Inside the inner function, yet another function is returned. This third function takes a single parameter c.
  • Finally, inside the third function, the result of multiplying a, b, and c together is returned.

This structure of nested functions allows us to call mul with one argument at a time, creating a chain of function calls. This is known as currying.

mul(1)(2)(3)

  • mul(1) returns a function that expects another argument.
  • (2) is passed to the returned function from the first step, resulting in
    (b) => { return (c) => { return 1 * 2 * c; }; }.
  • (3) is passed to the returned function from the second step, resulting in
    (c) => { return 1 * 2 * 3; }.
  • Finally, the innermost function is executed, resulting in 1 * 2 * 3, which equals 6.
00:00