Skip to curriculum
Jump to the editor

8.5. Keep adding until an empty call

Medium
Topics

This question is in

8. Currying and memoization
15–25 min

add(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

JAVASCRIPT
function add(...numbers) // returns a number, or a function that takes more numbers
  • Each call, to add or 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

  1. add(1)(2)(3)() returns 6, and add(5)() returns 5.
  2. add() returns 0.
  3. Every call with arguments returns a function, however long the chain is; a chain of 10,000 calls works.
  4. All the numbers in one call are added: add(1, 2)(3)() is 6.
  5. Every returned function can be used many times, and chains never affect each other.
  6. 0, negative numbers and decimals are added like any other number, from left to right, starting from 0.
  7. Only a call with no arguments ends the chain. A value whose type is not "number", undefined included, throws a TypeError at the call that passes it, and leaves the function that was called usable.

Examples

JAVASCRIPT
add(1)(2)(3)();     // 6
add(1, 2)(3, 4)();  // 10
add();              // 0
JAVASCRIPT
const fromThree = add(1)(2);
fromThree();        // 3
fromThree(10)();    // 13
fromThree(3)();     // 6: fromThree did not change
JAVASCRIPT
add(0)(0)();        // 0
add(1)(undefined);  // TypeError: undefined is an argument, not the end

Environment

  • Plain JavaScript in a browser page; the tests call the global add from add.js.
  • Every value of type "number" is accepted, NaN and Infinity included.
  • A version that ends on its own after three numbers is problem 8.4.

Hints

  1. What is the smallest thing each returned function needs to remember?
  2. How can a function tell f() from f(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…