Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
8.1. multiply(a)(b)
Easy
Topics
This question is in
8. Currying and memoizationMost 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
function multiply(a) // returns a function (b) => a times ba: the first factor, a number.- The returned function takes the second factor
band returns the product, a number.
Requirements
multiply(a)returns a function.multiply(a)(b)returns the numbera * b, not a function or a string.- A saved
multiply(a)can be called again and again, and gives the right answer each time. - Two saved functions, such as
multiply(2)andmultiply(3), never affect each other. - The result is exactly what
a * bgives, for zero, negative numbers, decimals,-0,NaN,Infinityand big numbers: no rounding and no special cases.
Examples
multiply(3)(4); // 12
multiply(-2)(3); // -6const 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]multiply(-1)(0); // -0, as -1 * 0 is
multiply(Infinity)(0); // NaNEnvironment
- Plain JavaScript in a browser page; the tests call the global
multiplyfrommultiply.js. - Only numbers are passed in. Calls with more arguments, such as
multiply(3, 4)ormultiply(1)(2)(3), are not part of this problem (see problem 8.2 and problem 8.4).
Hints
- After
multiply(3)has returned, its parameterais still needed. How can the returned function still read it? - 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…