leetcodedaybyday - Beats 100% with JavaScript - 100% with TypeScript
IntuitionThe problem requires us to create a function that maintains a counter, which starts at a given integer n and increments by 1 each time it is called. Th
# Intuition
The problem requires us to create a function that maintains a counter, which starts at a given integer `n` and increments by `1` each time it is called. The function should return the current value before incrementing.

# Approach
1. Define a function `createCounter(n)` that takes an integer `n` as input.
2. Inside the function:
   - Initialize a variable `count` with the value of `n`.
   - Return a nested function (closure) that:
     - Returns the current value of `count`.
     - Increments `count` by `1` for the next call.
3. Each time the returned function is called, it outputs the current value and updates `count` for the next invocation.

# Complexity
- **Time Complexity:** \( O(1) \) per function call, since it simply returns a stored variable and increments it.
- **Space Complexity:** \( O(1) \), as only a single integer variable is stored.

# Code
```javascript []
/**
 * @param {number} n
 * @return {Function} counter
 */
var createCounter = function(n) {
    let count = n;
    return function() {
        return count++;
    };
};

/** 
 * const counter = createCounter(10)
 * counter() // 10
 * counter() // 11
 * counter() // 12
 */
```
```typescript []
function createCounter(n: number): () => number {
    let count = n;
    return function() {
        return count++;
    }
}


/** 
 * const counter = createCounter(10)
 * counter() // 10
 * counter() // 11
 * counter() // 12
 */
```


['TypeScript', 'JavaScript']