Allow One Function Call | #2666 | LeetCode Solution

Author: neptune | 11th-Sep-2023
#JavaScript #LeetCode

Problem : Allow One Function Call | #2666 | LeetCode

Given a function `fn`, return a new function that is identical to the original function except that it ensures `fn` is called at most once.

  • The first time the returned function is called, it should return the same result as `fn`.

  • Every subsequent time it is called, it should return `undefined`.


Example 1:

Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]

Output: [{"calls":1,"value":6}]

Explanation:

const onceFn = once(fn);

onceFn(1, 2, 3); // 6

onceFn(2, 3, 6); // undefined, fn was not called

Example 2:

Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]

Output: [{"calls":1,"value":140}]

Explanation:

const onceFn = once(fn);

onceFn(5, 7, 4); // 140

onceFn(2, 3, 6); // undefined, fn was not called

onceFn(4, 6, 8); // undefined, fn was not called


Solution:

        /**

     * @param {Function} fn

     * @return {Function}

     */

    var once = function (fn) {


        let hasBeenCalled = false; // Initialize a flag to track whether fn has been called


        return function (...args) {

            if (!hasBeenCalled) {

                // If fn has not been called before

                hasBeenCalled = true; // Set the flag to true to indicate that fn has been called

                return fn(...args); // Call fn with the provided arguments and return its result

            } else {

                // If fn has already been called

                return undefined; // Return undefined as specified

            }

        };

    };


    /**

     * let fn = (a,b,c) => (a + b + c)

     * let onceFn = once(fn)

     *

     * onceFn(1,2,3); // 6

     * onceFn(2,3,6); // returns undefined without calling fn

     */



Explanation:

Let's break down the code step by step:


1. The code defines a function called `once` that takes a single parameter, `fn`, which is expected to be a function.


2. Inside the `once` function, a boolean variable named `hasBeenCalled` is initialized to `false`. This variable will be used to track whether the `fn` function has been called previously.


3. The `once` function returns a new function created using a closure. This new function accepts any number of arguments using the rest operator `...args`.


4. Inside the returned function:

   - It checks if `hasBeenCalled` is `false`, which means that the `fn` function has not been called before.

   - If `hasBeenCalled` is `false`, it sets `hasBeenCalled` to `true` to indicate that the `fn` function has now been called.

   - It then calls the original `fn` function with the provided arguments `...args` and returns its result.


5. If `hasBeenCalled` is `true`, indicating that the `fn` function has already been called previously, the returned function simply returns `undefined`, adhering to the behavior of allowing `fn` to be called at most once.


6. Below the `once` function, there's an example of how to use it:

   - It defines a function `fn` that takes three arguments and returns their sum.

   - It creates a new function `onceFn` by calling `once(fn)`. This new function, `onceFn`, is now capable of ensuring that `fn` is called at most once.


7. It demonstrates the usage of `onceFn`:

   - The first call to `onceFn(1, 2, 3)` returns `6` because it calls the original `fn` function and calculates the sum of the arguments.

   - The second call to `onceFn(2, 3, 6)` returns `undefined` without calling the original `fn` function again, as it has already been called once.


In summary, the `once` function creates a wrapper function that ensures the original function `fn` is called only once. Subsequent calls to the wrapper function return `undefined` to prevent additional calls to `fn`. This is achieved by using a flag (`hasBeenCalled`) to keep track of whether `fn` has been called before.






Related Blogs
To Be Or Not To Be | #2704 | LeetCode Solution
Author: neptune | 03rd-Sep-2023
#JavaScript #LeetCode
Write a function that helps developers test their code. It should take in any value and return an object with the following two functions...

Apply Transform Over Each Element in Array | #2635 | LeetCode Solution
Author: neptune | 05th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element...

Counter | #2620 | LeetCode Solution
Author: neptune | 02nd-Sep-2023
#JavaScript #LeetCode
Given an integer n, return a counter function. This counter function returns n and then n + 1, n + 2, etc...

Function Composition | #2629 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions...

Counter 2 | #2665 | LeetCode Solution
Author: neptune | 04th-Sep-2023
#JavaScript #LeetCode
Write function 'createCounter' It accept an initial integer 'init' It should return an object with three functions- increment() , decrement(), reset()...

Arrow Functions in JavaScript | ES6
Author: neptune | 26th-Mar-2023
#JavaScript #React.js
In this article, we will explore the syntax and usage of arrow functions in detail, along with some examples...

Array Reduce Transformation | #2626 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an integer array `nums` and a reducer function `fn`, and an initial value `init`, return a reduced array...

Add Two Promises | #2723 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
Given two promises `promise1` and `promise2`, return a new `promise`. `promise1` and `promise2` will both resolve with a number...

Different ways to handle state in React applications
Author: neptune | 21st-Jun-2023
#JavaScript #React.js
This article explores different ways to manage states in React, including local component state, context API, and state management libraries like Redux...

Filter Elements from Array | #2634 | LeetCode Solution
Author: neptune | 06th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a filtering function `fn`, return a filtered array `filteredArr`...

Is Object Empty | #2727 | LeetCode | JavaScript Solution
Author: neptune | 01st-Sep-2023
#JavaScript #LeetCode
Given an object or an array, return if it is empty...

Chunk Array | #2677 | LeetCode Solution
Author: neptune | 19th-Sep-2023
#JavaScript #LeetCode
Given an array arr and a chunk `size`, return a `chunked` array...

Managing Virtual Environments in React JavaScript Projects
Author: neptune | 28th-Jun-2023
#JavaScript #React.js
Virtual environments are a valuable tool in React JavaScript projects as they allow developers to isolate dependencies, manage package versions, and maintain project consistency...

Memoize | #2634 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value...

Array Prototype Last | #2619 | LeetCode Solution
Author: neptune | 20th-Sep-2023
#JavaScript #LeetCode
Write code that enhances all arrays such that you can call the `array.last()` method on any array and it will return the last element...

All You Need to Know About Pure Functions & Impure Functions in JavaScript
Author: neptune | 02nd-Apr-2023
#JavaScript #React.js
You should try to use pure functions whenever possible and avoid using impure functions unless necessary...

A Guide to Writing Clean, Readable, and Maintainable Code in JavaScript
Author: neptune | 23rd-Feb-2024
#JavaScript
By incorporating these principles into your coding practices, you contribute to creating code that is not only functional but also maintainable and easily understandable by your peers...

From REST to GraphQL: The Future of API Design
Author: neptune | 25th-Feb-2024
#JavaScript
Unlike traditional REST APIs, GraphQL provides a more flexible and intuitive approach to data querying and retrieval...

6 Brilliant JavaScript Frameworks for Every Developer
Author: neptune | 16th-Feb-2024
#JavaScript
JavaScript's web development with frameworks like Synaptic.js for neural networks, OpenCV.js for multimedia processing, D3.js for dynamic data visualizations, Compromise.js for efficient NLP, ConvNet...

State in React: Component State and Controlling Behavior
Author: neptune | 21st-Feb-2024
#JavaScript #React.js
React, a popular JavaScript library for building user interfaces, introduces the concept of state and lifecycle methods to help developers manage the dynamic nature of components...

Decode Secret Language of React: Game-Changer for Web Developers
Author: neptune | 25th-Feb-2024
#JavaScript #React.js
JSX is a syntax extension for JavaScript recommended by React for describing what the UI should look like...

View More