Skip to curriculum
Jump to the editor

6.2. A counter with increment, decrement and reset

Easy
Topics

This question is in

6. Functions and closures
10–15 min

A cart badge shows how many items are in the cart. A plus button adds one, a minus button removes one, and "Clear" goes back to where it started. Three handlers have to change the same number, and nothing else on the page should be able to set it to something odd.

Write createCounter(initial) in counter.js. It returns an object with four methods that share one private count. The methods are often passed around on their own (button.onclick = counter.increment), so each must work without being called on the object.

Signature

JAVASCRIPT
function createCounter(initial) // returns { get, increment, decrement, reset }
  • initial: the starting count. A missing initial (or undefined) counts as 0.
  • get() returns the current count.
  • increment() adds 1 and returns the new count.
  • decrement() subtracts 1 and returns the new count. The count may go below zero.
  • reset() sets the count back to initial and returns it.

Requirements

  1. createCounter returns an object whose get, increment, decrement and reset are functions, and no other own properties.
  2. The count starts at initial, or 0 when initial is missing.
  3. increment and decrement change the count by one and return the new count; get only reads it.
  4. reset returns to initial (not to 0) and returns it; counting goes on from there.
  5. Every method works when taken off the object and called on its own, or with any this.
  6. Counters made by separate calls are independent.
  7. The count is private: setting or replacing properties on the returned object never changes what the methods see.

Examples

JAVASCRIPT
const counter = createCounter(5);
counter.increment(); // 6
counter.increment(); // 7
counter.decrement(); // 6
counter.get();       // 6
counter.reset();     // 5
JAVASCRIPT
const { increment, get } = createCounter();
increment();
increment();
get(); // 2: the methods do not need the object
JAVASCRIPT
const counter = createCounter();
counter.decrement(); // -1
counter.count = 100; // a new property, not the count
counter.get();       // -1

Environment

  • Plain JavaScript in a browser page; the tests call the global createCounter from counter.js.
  • initial is always a number or missing.
  • Out of scope: steps other than 1, limits, and listeners for changes.

Hints

  1. If a method reads this.count, what happens when it is called as increment() on its own?
  2. reset needs the starting value long after createCounter returned. Is it still reachable?

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…