Day 8 - 30 Days LeetCode JavaScript Challenge: 2666. Allow One Function Call

Опубликовано: 23 Март 2026
на канале: vanAmsen
134
6

In today's JavaScript tutorial, we're diving into the intriguing realm of closures and function calls, as we take on the LeetCode challenge "2666. Allow One Function Call". A crucial problem to understand, this challenge holds immense value in enhancing your JavaScript proficiency, especially in the world of higher-order functions.

In this task, we're given a function fn and are asked to create a new function that behaves identically to the original fn but with a twist. This new function must ensure that fn is invoked only once. So, irrespective of the number of times we call our new function, it will return the result of fn just once and return undefined for all subsequent calls.

To implement this, we use the concept of closures in JavaScript, a potent feature that allows functions to remember and access variables from an outer function scope, even after the outer function has finished execution. We create a flag hasBeenCalled within the scope of once function but outside the returned function. This flag helps us track whether fn has been called before or not. For the first call, we store the result of fn in result, set hasBeenCalled to true and return the result. From the second call onwards, since hasBeenCalled is already true, we bypass calling fn and return result, which will now be undefined as fn isn't called.

Understanding and implementing this challenge will equip you with a deeper knowledge of closures, function calls, and control flow in JavaScript, invaluable skills for any JavaScript developer. Follow along as we dissect this problem and remember - if you want to become a better programmer, every challenge solved brings you one step closer to your goal!