callAfter
Returns a new function that can be called only after calling a specific number of times.
1. Code
/**
* Creates a function that delays the execution of the provided function until it has been called a specified number of times.
*
* @param fn - The function to be called after a certain number of invocations.
* @param count - The number of times the function needs to be called before it is executed.
* @returns A new function that delays the execution of the provided function until it has been called a specified number of times.
*/
const callAfter = <T, S extends any[]>(
fn: (...args: S) => T,
count: number
): ((...args: S) => T | undefined) => {
let counter = 0;
return (...args: S): T | undefined => {
if (counter < count) {
counter++;
return undefined;
}
return fn(...args);
};
};
export default callAfter;
2. Installation
npx @jrtilak/lazykit@latest add callAfter -ts
3. Description
The callAfter
function is used to create a new function that can be called only after calling a specific number of times. Before the specified number of calls, the function will always return undefined
without executing the original function.
4. Props
Prop
Type
Default Value
function*Function---
count*number---
5. Examples
import callAfter from ".";
const fn = (x: number) => x + 1;
const callAfterFn = callAfter(fn, 2);
const result1 = callAfterFn(1);
// Expected Output: undefined
const result2 = callAfterFn(2);
// Expected Output: undefined
const result3 = callAfterFn(3);
// Expected Output: 4 : as the function `fn` has been called twice already.