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
- Host: GitHub
- URL: https://github.com/muawiya-contact/2620.-counter
- Owner: Muawiya-contact
- Created: 2025-04-22T13:09:54.000Z (6 months ago)
- Default Branch: main
- Last Pushed: 2025-04-22T13:23:10.000Z (6 months ago)
- Last Synced: 2025-04-22T14:25:20.848Z (6 months ago)
- Topics: challenge, coding-moves, functional-programming, leetcode, leetcode2620, problem-solving
- Language: JavaScript
- Homepage:
- Size: 5.86 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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