Skip to curriculum
Jump to the editor

8.1. multiply(a)(b)

Easy
Topics

This question is in

8. Currying and memoization
5–10 min

Most functions take all their arguments in one call: multiply(3, 4). A curried function takes them one call at a time: multiply(3)(4). The first call does not compute anything; it remembers 3 and hands back a function that waits for the second number. That half-finished function is useful on its own: const double = multiply(2) can be passed to map, saved in an object, or called many times.

Write multiply(a) in multiply.js. It returns a function; calling that function with b returns a * b.

Signature

JAVASCRIPT
function multiply(a) // returns a function (b) => a times b
  • a: the first factor, a number.
  • The returned function takes the second factor b and returns the product, a number.

Requirements

  1. multiply(a) returns a function.
  2. multiply(a)(b) returns the number a * b, not a function or a string.
  3. A saved multiply(a) can be called again and again, and gives the right answer each time.
  4. Two saved functions, such as multiply(2) and multiply(3), never affect each other.
  5. The result is exactly what a * b gives, for zero, negative numbers, decimals, -0, NaN, Infinity and big numbers: no rounding and no special cases.

Examples

JAVASCRIPT
multiply(3)(4);        // 12
multiply(-2)(3);       // -6
JAVASCRIPT
const double = multiply(2);
const triple = multiply(3);
double(5);             // 10
triple(5);             // 15
double(0.5);           // 1
[1, 2, 3].map(double); // [2, 4, 6]
JAVASCRIPT
multiply(-1)(0);       // -0, as -1 * 0 is
multiply(Infinity)(0); // NaN

Environment

  • Plain JavaScript in a browser page; the tests call the global multiply from multiply.js.
  • Only numbers are passed in. Calls with more arguments, such as multiply(3, 4) or multiply(1)(2)(3), are not part of this problem (see problem 8.2 and problem 8.4).

Hints

  1. After multiply(3) has returned, its parameter a is still needed. How can the returned function still read it?
  2. Is there anything to compute before the second number arrives?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…