Write a function `createCounter()` that returns an object with `increment()`, `decrement()`, and `getCount()` methods. The count starts at 0.
Problem Statement
Examples
Input: const c = createCounter(); c.increment(); c.getCount();
Output: 1
Explanation: Counter internal state incremented from 0 to 1.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Create a Counter with Closures, we consider the execution characteristics of JavaScript engines. Write a function `createCounter()` that returns an object with `increment()`, `decrement()`, and `getCount()` methods. The count starts at 0. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (closures allow inner functions to access variables from the outer function).
- Implement Logic: Handle state and transformations efficiently (declare a count variable inside createcounter and return methods that modify it).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function createCounter() {
let count = 0;
return {
increment: () => ++count,
decrement: () => --count,
getCount: () => count
};
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.