AI solution for JavaScript Coding Question on BFE.dev
46. implement `_.once()`
One possible implementation of once()
in JavaScript is as follows:
function once(fn) { let called = false; let result; return function(...args) { if (!called) { called = true; result = fn(...args); } return result; };}
This implementation creates a closure over the original function fn
, a called
flag, and the result
of the original function. It then returns a new anonymous function that takes any number of arguments using the rest operator (...args
).
When the new function is called for the first time, it checks if called
is false
, meaning that the original function has not yet been called. If this is the case, it sets called
to true
, calls fn
with the provided arguments using the spread operator (...args
), and stores the result in result
.
For subsequent calls, the new function checks if called
is true
, meaning that the original function has already been called. If this is the case, it simply returns the stored result
.
This implementation ensures that the original function is called only once, and that subsequent calls return the result of the first call.