[Easy] LeetCode JS 30 - 2666. Allow One Function Call

March 5, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2666. Allow One Function Call

Question Prompt

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

Solutions

Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!

First, create a function called once. It takes another function as its argument. Its primary goal is to return a new function that mimics the original, but with the 'call once' restriction.

Inside once, we can use closure by creating a variable called, which is a flag to tell us if the original function has been run yet.

once will return a function. Within the function, we ask "has the original function been called before?" by checking if (!called) . If it’s not called yet, we set the called flag to true, marking that it's been executed. Then, call the original function and return the value.

Otherwise, for all other calls, we simply return undefined;.

function once(fn) {
  let called = false;

  return function (...args) {
    if (!called) {
      called = true;
      return fn(...args); // Return the result here
    }

    // Return undefined for subsequent calls
    return undefined;
  };
}
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee