callAfter
Returns a new function that can be called only after calling a specific number of times.
1./**2.* Returns a new function that can be called only after calling a specific number of times.3.**/4.const callAfter = <T, S extends any[]>(5.fn: (...args: S) => T,6.count: number,7.): ((...args: S) => T | undefined) => {8.let counter = 0;9.return (...args: S): T | undefined => {10.if (counter < count) {11.counter++;12.return undefined;13.}14.return fn(...args);15.};16.};17.18.export default callAfter;
1. Installtion
npx @jrtilak/lazykit add callAfter
2. Parameters
-
fn
((...args: S) => T
)
The function to be called after the specified count. This function will receive the same arguments that are passed to the returned function. -
count
(number
)
The number of times the returned function must be called beforefn
is executed.
3. Returns
((...args: S) => T | undefined)
Returns a new function that, when called, will only executefn
after it has been called the specified number of times. Until that point, it will returnundefined
.
4. Type Parameters
-
T
The return type of the functionfn
. -
S
The type of the arguments accepted by the functionfn
. This allows the returned function to accept the same parameters asfn
, ensuring type safety.
5. Usage
The callAfter
utility creates a wrapper function that delays execution of the provided function fn
until it has been called a specified number of times. Each call increments an internal counter until it reaches the count
threshold. Once the threshold is met, fn
is executed with the given arguments, returning its result. Before the threshold, the function returns undefined
.
1. Example
1.import callAfter from "@/utils/callAfter";2.3.// Create a function that logs a message4.const logMessage = (msg) => console.log(msg);5.6.// Set up a delayed function that only executes after 3 calls7.const delayedLog = callAfter(logMessage, 3);8.9.delayedLog("Hello"); // No output10.delayedLog("Hello"); // No output11.delayedLog("Hello"); // No output12.delayedLog("Hello again!"); // Logs "Hello again!" immediately on 4th call13.delayedLog("Hello again! 2");
This utility is useful when you want to delay function execution until a specific event or condition occurs multiple times, making it ideal for situations where you only want an action to occur after several triggers or validations.