once
Returns a new function that can be called only once.
1. Code
/**
* Creates a function that can only be called once. Subsequent calls to the function will return undefined.
*
* @param fn - The function to be called once.
* @returns A new function that can only be called once.
*/
const once = <T, S extends any[]>(
fn: (...args: S) => T
): ((...args: S) => T | undefined) => {
let isCalled = false;
return (...args: S): T | undefined => {
if (!isCalled) {
isCalled = true;
return fn(...args);
}
return undefined;
};
};
export default once;
2. Installation
npx @jrtilak/lazykit@latest add once -ts
3. Description
The once
function is used to create a new function that can be called only once. After the first call, the function will always return undefined without executing the original function.
This is useful when you want to ensure that a function is called only once, regardless of how many times it is called. For example, a subscribe button on a website should only be clicked once, and the function should not be executed again if the button is clicked multiple times.
4. Props
Prop
Type
Default Value
function*Function---
5. Examples
import once from ".";
const subscribe = once(() => {
console.log("Subscribed");
});
const result = subscribe();
// Expected Output: Subscribed
const result2 = subscribe();
// Expected Output: undefined : as the function has been called once already.