Counter Function Using Closures in JavaScript
Intuition\nThe problem involves generating a counter function that starts from a given integer n and increments its value each time the function is called. Usin
# Intuition\nThe problem involves generating a counter function that starts from a given integer n and increments its value each time the function is called. Using a closure is an ideal solution since closures allow functions to retain access to variables from their lexical scope, even after the outer function has executed. This way, the inner function can remember and update the value of n between calls.\n\n# Approach\nWe create a function createCounter that:\n\n\t1.\tAccepts an integer n as input.\n\t2.\tReturns an inner function (closure) that:\n\t\u2022\tReturns the current value of n.\n\t\u2022\tIncrements n for the next call.\n\nThe inner function \u201Cremembers\u201D the variable n from the outer function due to JavaScript closures. Each time the returned function is invoked, it increments n and provides the desired output.\n\n# Complexity\n- Time complexity:\n$$O(1)$$\nEach call to the counter function executes in constant time as it involves just returning and incrementing a variable.\n\n- Space complexity:\n$$O(1)$$\nThe space usage is constant, as we only maintain the variable n and the closure for the function.\n\n# Code\n```javascript []\n/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n    // Define and return a function (closure) that captures `n`\n    return function() {\n        // Return the current value of `n` and then increment it by 1 for the next call\n        return n++;\n    };\n};\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */\n```
['JavaScript']