The _.once()
function from lodash creates a new function that can only be called once. The first time the function is called, it will execute the original function passed in. Subsequent calls to the new function will return the same result as the first call.
Here's an example demonstrating the use of _.once()
in JavaScript:
index.tsx222 chars11 lines
In this example, we import the once
function from lodash using the destructuring syntax. We then define our original function doSomething()
, which simply logs a message to the console.
Next, we create a new function doSomethingOnce
using once(doSomething)
. This returns a new function that, when called for the first time, will execute doSomething()
. Subsequent calls to doSomethingOnce()
do nothing.
Finally, we call doSomethingOnce()
twice to demonstrate this behavior. The first call logs our message to the console, and the second call does nothing.
gistlibby LogSnag