once

Returns a new function that can be called only once.

1.
/**
2.
* Returns a new function that can be called only once.
3.
**/
4.
const once = <T, S extends any[]>(
5.
fn: (...args: S) => T,
6.
): ((...args: S) => T | undefined) => {
7.
let isCalled = false;
8.
return (...args: S): T | undefined => {
9.
if (!isCalled) {
10.
isCalled = true;
11.
return fn(...args);
12.
}
13.
return undefined;
14.
};
15.
};
16.
17.
export default once;

1. Installtion

npx @jrtilak/lazykit add once

2. Parameters

  • fn ((...args: S) => T)
    The function to be called only once. This function will receive the same arguments that are passed to the returned function.

3. Returns

  • ((...args: S) => T | undefined)
    Returns a new function that, when called, will invoke fn only once. Subsequent calls will return undefined.

4. Type Parameters

  • T
    The return type of the function fn.

  • S
    The type of the arguments accepted by the function fn. This allows the returned function to accept the same parameters as fn, ensuring type safety.

5. Usage

The once function wrapper ensures that a provided function can only be called once. Any subsequent calls to the returned function will be ignored, returning undefined instead of executing the function again.

1. Example

1.
import once from "@/utils/once";
2.
3.
// Function that we want to run only once
4.
const initialize = () => console.log("Initialization completed!");
5.
6.
const initializeOnce = once(initialize);
7.
8.
// Call the function multiple times
9.
initializeOnce(); // Output: Initialization completed!
10.
initializeOnce(); // No output
11.
initializeOnce(); // No output

In this example, initialize is executed only on the first call to initializeOnce. All subsequent calls will be ignored, making it useful for setup functions that should only run once.