callBefore
Returns a new function that can be called only for specific number of times.
1. Code
/**
* Calls the provided function `fn` only for the first `count` invocations,
* and returns `undefined` for subsequent invocations.
*
* @template T - The return type of the function `fn`.
* @template S - The argument types of the function `fn`.
* @param {(...args: S) => T} fn - The function to be called.
* @param {number} count - The number of times the function `fn` should be called.
* @returns {(...args: S) => T | undefined} - A function that calls `fn` only for the first `count` invocations.
*/
const callBefore = <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 fn(...args);
}
return undefined;
};
};
export default callBefore;
2. Installation
npx @jrtilak/lazykit@latest add callBefore -undefined
3. Description
The callBefore
function is used to create a new function that can be called only for a specific number of times. After the specified number of calls, the function will always return undefined
without executing the original function.
This is useful in some scenarios like rate limiting
or trial period
where you want to allow a function to be called only for a specific number of times.
4. Props
Prop
Type
Default Value
function*Function---
count*number---
5. Examples
import callBefore from ".";
const fn = (x: number) => x + 1;
const callBeforeFn = callBefore(fn, 2);
const result1 = callBeforeFn(1);
// Expected Output: 2
const result2 = callBeforeFn(2);
// Expected Output: 3
const result3 = callBeforeFn(3);
// Expected Output: undefined : as the function `fn` has been called twice already.