Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
8.5. Keep adding until an empty call
Medium
Topics
This question is in
8. Currying and memoizationadd(1)(2)(3)() has no fixed number of calls. Each call with numbers adds them and hands back a function for more; the call with no arguments says "that's all" and gets the total. The same pattern shows up in builders and query chains, where you keep adding parts and a final call produces the result. The hard parts are telling "no arguments" apart from "an argument that is undefined", and keeping every half-finished chain reusable.
Write add in add.js.
Signature
function add(...numbers) // returns a number, or a function that takes more numbers- Each call, to
addor to a function it returned, takes zero or more numbers. - A call with one or more arguments returns a function that takes more numbers in the same way.
- A call with no arguments returns the total of every number added before it in that chain, a number.
Requirements
add(1)(2)(3)()returns6, andadd(5)()returns5.add()returns0.- Every call with arguments returns a function, however long the chain is; a chain of 10,000 calls works.
- All the numbers in one call are added:
add(1, 2)(3)()is6. - Every returned function can be used many times, and chains never affect each other.
0, negative numbers and decimals are added like any other number, from left to right, starting from 0.- Only a call with no arguments ends the chain. A value whose type is not
"number",undefinedincluded, throws aTypeErrorat the call that passes it, and leaves the function that was called usable.
Examples
add(1)(2)(3)(); // 6
add(1, 2)(3, 4)(); // 10
add(); // 0const fromThree = add(1)(2);
fromThree(); // 3
fromThree(10)(); // 13
fromThree(3)(); // 6: fromThree did not changeadd(0)(0)(); // 0
add(1)(undefined); // TypeError: undefined is an argument, not the endEnvironment
- Plain JavaScript in a browser page; the tests call the global
addfromadd.js. - Every value of type
"number"is accepted,NaNandInfinityincluded. - A version that ends on its own after three numbers is problem 8.4.
Hints
- What is the smallest thing each returned function needs to remember?
- How can a function tell
f()fromf(undefined)?
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…