Make Counter IILoading saved progress…

Make Counter II

A follow-up to Make Counter. In v1 you returned a single function that yielded the next integer; here you return a richer object — one that you can read from, increment, decrement, and reset back to its starting value. The state of each counter you create is fully independent of every other.

Implement makeCounterII(initial = 0). It returns an object with four methods: value, increment, decrement, and reset. increment and decrement return the new value (handy for chaining a console.log onto the call), and reset puts the counter back to whatever initial was passed in — not zero, not the most recent value. Two calls to makeCounterII produce two independent counters. The teaching point is the same as v1's — see MDN on closures if the term is unfamiliar — but applied to a small object of methods sharing one private variable.

Signature

function makeCounterII(initial = 0) {
  // returns { value, increment, decrement, reset }
  // value()     -> current count
  // increment() -> count + 1 (and returns the new value)
  // decrement() -> count - 1 (and returns the new value)
  // reset()     -> initial   (and returns the initial value)
}

Examples

const c = makeCounterII();
c.value();     // 0
c.increment(); // 1
c.increment(); // 2
c.decrement(); // 1
c.value();     // 1
// Two counters are independent
const a = makeCounterII(0);
const b = makeCounterII(10);
a.increment(); // 1
a.increment(); // 2
b.decrement(); // 9
a.value();     // 2  — a is untouched by b
b.value();     // 9
// reset goes back to the original initial value, not to 0
const c = makeCounterII(5);
c.increment(); // 6
c.increment(); // 7
c.decrement(); // 6
c.reset();     // 5
c.value();     // 5

Notes

  • Reset targetreset() returns the counter to the initial value that was passed to makeCounterII, not to 0 and not to the most recent value. makeCounterII(5) resets to 5.
  • Independent state — every call to makeCounterII must yield a counter with its own private count. Two counters can never share or stomp on each other.
  • Return valuesincrement, decrement, and reset each return the new value of the counter. value also returns the current value but does not change it.
  • No clampingdecrement below zero is allowed (makeCounterII(0).decrement() returns -1). The counter is just an integer; you don't need a floor.
  • Default initialmakeCounterII() with no argument starts at 0.
  • No globals — keep the state inside the closure, not on window, module.exports, or any shared object.
Loading editor…