An open API service indexing awesome lists of open source software.

https://github.com/muawiya-contact/2620.-counter

# 2620. Counter
https://github.com/muawiya-contact/2620.-counter

challenge coding-moves functional-programming leetcode leetcode2620 problem-solving

Last synced: 2 months ago
JSON representation

# 2620. Counter

Awesome Lists containing this project

README

          

# ๐Ÿ”ข LeetCode Easy: 2620. Counter

## ๐Ÿ“„ Problem Statement

You are given an integer `n`. Return a **counter function** that returns `n` on the first call, then returns `n + 1`, then `n + 2`, and so on for each subsequent call.

### ๐Ÿงพ Function Signature

``` js
function createCounter(n: number): () => number
```
# ๐Ÿงช Example 1
## Input:
```
const counter = createCounter(10);
```
## Calls:
```
counter(); // 10
counter(); // 11
counter(); // 12
```
## Output:
```
[10, 11, 12]
```
# ๐Ÿ’ก Key Concepts
+ Closure: A function that "remembers" the environment in which it was created.

+ The returned function can access and modify the variable n from its outer function scope.

+ This problem is great for practicing functional programming and understanding JavaScript's closure behavior.
# โœ… JavaScript Solution
javascript
```
/**
* @param {number} n
* @return {Function} counter
*/
var createCounter = function(n) {
return function() {
const current = n;
n += 1;
return current;
};
};

/**
* const counter = createCounter(10);
* console.log(counter()); // 10
* console.log(counter()); // 11
* console.log(counter()); // 12
*/

```
# ๐Ÿง  Why It Works
+ The outer function createCounter(n) returns a new function.

+ This returned function retains access to n even after createCounter has finished executing.

+ Each call to the counter updates and returns the current value of n.

# ๐Ÿ“Š Complexity Analysis

Type | Complexity
Time (per call) | O(1)
Space | O(1)

# ๐Ÿ“š Useful Topics
+ JavaScript Closures

+ Functional Programming

+ Lexical Scoping

+ State Persistence via Closure

# ๐Ÿ‘จโ€๐Ÿ’ป Author
Muawiya โ€“ AI Student & Mathematician
Founder of โšก[ Coding Moves](https://www.youtube.com/@Coding_Moves)

> *Passionate about building intelligent systems and mastering the art of programming.*

๐Ÿ“ฃ Follow Coding Moves
๐Ÿ”— YouTube: @Coding_Moves
๐Ÿ”— GitHub: Muawiya-contact
๐Ÿ”— LinkedIn: Connect with Muawiya