Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
8.4. sum(a)(b)(c) with any grouping
Medium
Topics
This question is in
8. Currying and memoizationsum(1)(2)(3) is a classic way to check that you understand closures: each call returns a function that remembers the numbers so far. Real callers rarely stick to one number per call, though. A version that also accepts sum(1, 2)(3), sum(1)(2, 3) and sum(1, 2, 3) has to count the numbers it has, whatever the grouping, and it has to keep every half-finished call reusable.
Write sum in sum.js. It adds three numbers that arrive over one or more calls, in any grouping.
Signature
function sum(...numbers) // returns a number, or a function that waits for more numbers- Each call, to
sumor to a function it returned, takes zero or more numbers. - While fewer than three numbers have arrived in total, the call returns a function that takes the next numbers in the same way.
- The call that brings the count to three or more returns the total of every number received.
Requirements
sum(1)(2)(3),sum(1, 2)(3),sum(1)(2, 3)andsum(1, 2, 3)all return6, a number.- With fewer than three numbers, a call returns a function.
- Every returned function can be called many times, and returned functions never affect each other or later calls to
sum. - A call with no arguments adds nothing and returns a function that still waits.
0, negative numbers and decimals count like any other number. The numbers are added from left to right, starting from 0, asa + b + cdoes.- Numbers past the third, given in the completing call, are added too:
sum(1, 2)(3, 4)is10. - A value whose type is not
"number"(a numeric string,undefined,null, an array) throws aTypeErrorat the call that passes it, and leaves the function that was called usable.
Examples
sum(1)(2)(3); // 6
sum(1, 2)(3); // 6
sum(1)(2, 3); // 6
sum(1, 2, 3); // 6const fromThree = sum(1)(2);
fromThree(3); // 6
fromThree(10); // 13: fromThree did not change
sum()(1)()(2)(3); // 6: empty calls add nothingsum(0)(0)(0); // 0, not a function
sum(1, 2)(3, 4); // 10
sum(1)("2"); // TypeErrorEnvironment
- Plain JavaScript in a browser page; the tests call the global
sumfromsum.js. - Every value of type
"number"is accepted,NaNandInfinityincluded. - A sum with no fixed count, ended by an empty call, is problem 8.5. A general
curryhelper is problem 8.2.
Hints
- What does each returned function need to remember, and how can it remember it without sharing it with the other returned functions?
- When should the check for a wrong type happen so that nothing has been added yet?
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…