callBefore

Returns a new function that can be called only for specific number of times.

1.
/**
2.
* Returns a new function that can be called only for specific number of times.
3.
**/
4.
const callBefore = <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 fn(...args);
13.
}
14.
return undefined;
15.
};
16.
};
17.
18.
export default callBefore;

1. Installtion

npx @jrtilak/lazykit add callBefore

2. Parameters

  • fn ((...args: S) => T)
    The function to be called a specified number of times. This function will receive the same arguments that are passed to the returned function.

  • count (number)
    The number of times the returned function is allowed to invoke fn. After this count is reached, further calls will return undefined.

3. Returns

  • ((...args: S) => T | undefined)
    Returns a new function that, when called, will execute fn for the specified number of times. Once the count is reached, 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 callBefore utility creates a function wrapper that allows the provided function fn to execute only for the first count calls. After reaching the count threshold, further calls will return undefined, making it useful for limiting how often a function can run.

1. Example

1.
import callBefore from "@/utils/callBefore";
2.
3.
// Define a function that logs a message
4.
const logMessage = (msg) => console.log(msg);
5.
6.
// Create a limited function that only logs for the first 2 calls
7.
const limitedLog = callBefore(logMessage, 2);
8.
9.
limitedLog("Hello"); // Logs "Hello"
10.
limitedLog("Hello again!"); // Logs "Hello again!"
11.
limitedLog("This will not be logged"); // No output
12.
limitedLog("Still no output"); // No output

In this example, limitedLog only executes logMessage for the first two calls. Subsequent calls after reaching the threshold simply return undefined without executing the function, which can be useful for rate-limiting or pre-conditionally restricting function calls.