Make Counter
JS Functions
Easy
10 min
closures
Implement makeCounter(initial = 0, step = 1). It returns a function counter. Each call to counter() returns the current value and then advances it by step.
const counter = makeCounter();
counter(); // 0
counter(); // 1
counter(); // 2
const countdown = makeCounter(10, -5);
countdown(); // 10
countdown(); // 5
countdown(); // 0
countdown.reset();
countdown(); // 10
Requirements
- The first call returns
initial. Every later call returns the previous value plusstep. initialdefaults to0andstepdefaults to1.- Counters are independent: each call to
makeCounterhas its own state. - The state must be private. It cannot be read or changed except through the counter (no global variables, and no public
countproperty). counter.reset()puts the counter back toinitial, so the next call returnsinitialagain.
Follow-up
- Rewrite it as a class with private fields (
#count). What changes? - Why does a closure keep
countalive aftermakeCounterhas returned? - How is this pattern related to React's
useState?
Spotted a mistake or a rights concern? Report an issue