before
Creates a new function that limits the number of times the given function (func) can be called.
Signature
typescript
function before<F extends (...args: any[]) => any>(
n: number,
func: F
): (...args: Parameters<F>) => ReturnType<F> | undefined;Parameters
n(number): The number of times the returned function is allowed to callfuncbefore stopping.- If
nis 0,funcwill not be called. - If
nis a positive integer,funcwill be called up ton-1times.
- If
func(F): The function to be called with the limit applied.
Returns
((...args: Parameters<F>) => ReturnType<F> | undefined): A new function that:
- Tracks the number of calls.
- Invokes
funcuntil then-1-th call. - Returns
undefinedif the number of calls reaches or exceedsn, stopping further calls.
Error
Throws an error if n is negative.
Example
typescript
import { before } from 'es-toolkit/function';
const beforeFn = before(3, () => {
console.log('called');
});
// Will log 'called'.
beforeFn();
// Will log 'called'.
beforeFn();
// Will not log anything.
beforeFn();Lodash Compatibility
Import before from es-toolkit/compat for full compatibility with lodash.
beforedoes not throw an error whennis negative.beforethrows an error iffuncis not a function.beforereturns the last result offuncwhen the number of calls reaches or exceedsn.
typescript
import { before } from 'es-toolkit/compat';
let count = 0;
const before3 = before(3, () => {
console.log('Incrementing count...');
return ++count;
});
console.log(before3()); // Incrementing count... => 1
console.log(before3()); // Incrementing count... => 2
console.log(before3()); // => 2
