Counter : Closure
Intuition\nThe code snippet defines a function createCounter that takes an integer n as input and returns another function that increments and returns a counter
# Intuition\nThe code snippet defines a function `createCounter` that takes an integer n as input and returns another function that increments and returns a counter variable count every time it is called.\n\n# Approach\nThe inner function returned by `createCounter` uses a `closure` to maintain access to the `count` variable defined in the outer function. When the inner function is called, it increments `count` by 1 and returns its new value.\n\n# Complexity\n- Time complexity: \nThe time complexity of the inner function is `O(1)` because it performs a constant number of operations (incrementing and returning count). The time complexity of the outer function is also `O(1)` because it performs a constant number of operations (defining a variable and returning the inner function).\n\n- Space complexity:\nThe space complexity of the `createCounter` function is `O(1)` because it only defines one variable count. The space complexity of the inner function is also `O(1)` because it does not create any additional variables.\n\n# Code\n```\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n    let count = n - 1\n    return function() {\n        count++\n        return count\n    };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
['JavaScript']