Implement counter - create an independent counter object backed by closure state.
1) Input
- Accept an optional initial number
initialValue. - If omitted, default to
0.
2) Output API
- Return an object with two methods:
increment(): increase by 1 and return the new value.decrement(): decrease by 1 and return the new value.
3) State model
- Each counter instance must keep independent state.
- Methods should rely on closed-over state (not shared/global state).
Examples
const c = counter(0)
c.increment() // 1
c.increment() // 2
c.decrement() // 1
const a = counter(10)
const b = counter(5)
a.increment() // 11
b.decrement() // 4