count
returns the result of a function and the number of times that function is invoked.
1./**2.* returns the result of a function and the number of times that function is invoked.3.**/4.const count = <A extends any[], R>(fn: (...args: A) => R) => {5.let callCount = 0;6.7.const wrapper = (...args: A): R => {8.callCount++;9.const result = fn(...args);10.return result;11.};12.13.const getCount: () => number = () => callCount;14.wrapper.getCount = getCount;15.16.return wrapper;17.};18.19.export default count;
1. Installtion
npx @jrtilak/lazykit add count
2. Parameters
fn
((...args: A) => R
)
The function whose calls are to be counted. This function will receive the same arguments that are passed to the returned function.
3. Returns
((...args: A) => R) & { getCount: () => number }
Returns a new function (the wrapper) that, when called, invokesfn
and counts the number of times it has been called. The wrapper also includes agetCount
method that returns the number of times the function has been invoked.
4. Type Parameters
-
A
The type of the arguments accepted by the functionfn
. This allows the wrapper function to accept the same parameters asfn
, ensuring type safety. -
R
The return type of the functionfn
. This allows the wrapper function to return the same type asfn
.
1. Usage
The count
utility function wraps a given function fn
and keeps track of the number of times it’s called. It provides a getCount
method on the wrapper function, which returns the total count of calls.
2. Example
1.import count from "@/utils/count";2.3.// Define a function to count calls4.const add = (a, b) => a + b;5.6.// Wrap the function to enable call counting7.const countedAdd = count(add);8.9.// Call the function a few times10.console.log("Count: ", countedAdd.getCount());; // 011.12.console.log("Sum: ", countedAdd(3, 5)); // 813.console.log("Count: ", countedAdd.getCount()); // 114.15.console.log("Sum: ", countedAdd(2, 7));; // 916.console.log("Count: ", countedAdd.getCount());; // 217.18.console.log("Sum: ", countedAdd(1, 4));; // 519.console.log("Count: ", countedAdd.getCount());; // 3
In this example, countedAdd
acts as a normal function but tracks each time it's called. The getCount
method provides a way to access the current call count, making this utility useful for tracking usage metrics, debugging, or applying limits based on call frequency.