Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
6.2. A counter with increment, decrement and reset
Easy
Topics
This question is in
6. Functions and closuresA 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
function createCounter(initial) // returns { get, increment, decrement, reset }initial: the starting count. A missinginitial(orundefined) counts as0.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 toinitialand returns it.
Requirements
createCounterreturns an object whoseget,increment,decrementandresetare functions, and no other own properties.- The count starts at
initial, or0wheninitialis missing. incrementanddecrementchange the count by one and return the new count;getonly reads it.resetreturns toinitial(not to0) and returns it; counting goes on from there.- Every method works when taken off the object and called on its own, or with any
this. - Counters made by separate calls are independent.
- The count is private: setting or replacing properties on the returned object never changes what the methods see.
Examples
const counter = createCounter(5);
counter.increment(); // 6
counter.increment(); // 7
counter.decrement(); // 6
counter.get(); // 6
counter.reset(); // 5const { increment, get } = createCounter();
increment();
increment();
get(); // 2: the methods do not need the objectconst counter = createCounter();
counter.decrement(); // -1
counter.count = 100; // a new property, not the count
counter.get(); // -1Environment
- Plain JavaScript in a browser page; the tests call the global
createCounterfromcounter.js. initialis always a number or missing.- Out of scope: steps other than 1, limits, and listeners for changes.
Hints
- If a method reads
this.count, what happens when it is called asincrement()on its own? resetneeds the starting value long aftercreateCounterreturned. 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…