FrontendInterviews.dev

Loading problem…

114. Counter Function with Closure

Easy•
Acceptance: 94.12%
•
🔓3/3 Pro unlocks today

Implement counter - create an independent counter object backed by closure state.

Requirements

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

Constraints

  • Default initial value must be 0 when omitted.
  • increment() and decrement() must return the updated value.
  • Each counter instance must keep independent state.
  • Implementation should use closure state rather than shared/global storage.