Make CounterLoading saved progress…

Make Counter

You've probably reached for a let count = 0 at module scope to hand out incrementing IDs — for DOM elements, log lines, or React keys before you had a real id source. The catch is that a module-level variable is shared by everyone; if two parts of your app want their own counter, they collide. A factory fixes that: each call hands out a fresh, independent counter.

Implement makeCounter(start). It takes an integer start and returns a new function. Each call to that returned function yields the next value in the sequence, starting at start. Two counters made by two separate makeCounter calls must not share state. This is a closure exercise — see MDN on closures if the term is unfamiliar.

Signature

function makeCounter(start) {
  // returns a function () => number
  // 1st call -> start
  // 2nd call -> start + 1
  // 3rd call -> start + 2
  // ...
}

Examples

const next = makeCounter(5);
next(); // 5
next(); // 6
next(); // 7
const a = makeCounter(0);
const b = makeCounter(100);
a(); // 0
a(); // 1
b(); // 100
a(); // 2  <- a's state is untouched by b

Notes

  • Return then increment — the first call returns start itself, not start + 1. The next value is computed for the next call.
  • Independent counters — every makeCounter(...) call must give back a function with its own private state. They can never share or overwrite each other.
  • Default start — when makeCounter() is called with no argument, the counter starts at 0.
  • Integer sequence only — you don't need to handle floats, strings, or step arguments. Always +1 per call.
  • No globals — keep the state inside the closure, not on window, module.exports, or any shared object.
Loading editor…