Counter | #2620 | LeetCode Solution

Author: neptune | 02nd-Sep-2023

Problem : Counter | #2620 | LeetCode

Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).


Example 1:

Input: 

n = 10 

["call","call","call"]

Output: [10,11,12]

Explanation: 

counter() = 10 // The first time counter() is called, it returns n.

counter() = 11 // Returns 1 more than the previous time.

counter() = 12 // Returns 1 more than the previous time.

Example 2:

Input: 

n = -2

["call","call","call","call","call"]

Output: [-2,-1,0,1,2]

Explanation: counter() initially returns -2. Then increases after each sebsequent call.


Solution:

    /**

     * @param {number} n

     * @return {Function} counter

     */

    var createCounter = function(n) {

        return function() {

            return n++

        };

    };


    /**

     * const counter = createCounter(10)

     * counter() // 10

     * counter() // 11

     * counter() // 12

     */


Explanation:

The provided code defines a function `createCounter` that takes an integer `n` as an argument and returns another function. This returned function acts as a counter that starts at `n` and increments by 1 each time it's called. 

Let's break down the code and provide an explanation:


    var createCounter = function(n) {

        return function() {

            return n++;

        };

    };


1. `createCounter` is a function that takes an integer `n` as its parameter.


2. Inside `createCounter`, it returns another function (an anonymous function) that captures the value of `n`.


3. This inner function has no parameters and when called, it returns the current value of `n` and then increments `n` by 1 using the `n++` expression.



👉 Read More
Generate Fibonacci Sequence - JavaScript | Hackerank
Managing Virtual Environments in React JavaScript Projects
To Be Or Not To Be | #2704 | LeetCode Solution
Apply Transform Over Each Element in Array | #2635 | LeetCode Solution
Function Composition | #2629 | LeetCode Solution
Different ways to handle state in React applications
Chunk Array | #2677 | LeetCode Solution
Counter 2 | #2665 | LeetCode Solution
Array Reduce Transformation | #2626 | LeetCode Solution
Add Two Promises | #2723 | LeetCode Solution
Filter Elements from Array | #2634 | LeetCode Solution
Arrow Functions in JavaScript | ES6
From REST to GraphQL: The Future of API Design
Is Object Empty | #2727 | LeetCode | JavaScript Solution
How I Built My Blogging Website Using React, Node.js, and Jamstack Architecture?
How to Perform Unit Testing in React Components with Examples?
Do you know ! How to manage State in Functional & Class Components in React ?
A Guide to Writing Clean, Readable, and Maintainable Code in JavaScript
How to Get Started with Jamstack: A Comprehensive Guide?
Why, What, and When: Understanding Jamstack?
Explore more Blogs...