Skip to main content
Back to problems
#2665
Easy JavaScript

Counter ii

81.2% acceptance
Mar 2, 2026
888
37
Write a function createCounter. It should accept an initial integer init. It should return an object with three functions. The three functions are: increment() increases the current value by 1 and then returns it. decrement() reduces the current value by 1 and then returns it. reset() sets the current value to init and then returns it.

Solution

TypeScript
Time O(1)
Space O(1)
LeetCode
solution.ts
type Counter = {
  increment: () => number;
  decrement: () => number;
  reset: () => number;
};

function createCounter(init: number): Counter {
  let current = init;
  return {
  increment: () => ++current,
  decrement: () => --current,
  reset: () => {
    current = init;
    return current;
  },
  };
}

/**
 * const counter = createCounter(5)
 * counter.increment(); // 6
 * counter.reset(); // 5
 * counter.decrement(); // 4
 */