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, invokes fn and counts the number of times it has been called. The wrapper also includes a getCount method that returns the number of times the function has been invoked.

4. Type Parameters

  • A
    The type of the arguments accepted by the function fn. This allows the wrapper function to accept the same parameters as fn, ensuring type safety.

  • R
    The return type of the function fn. This allows the wrapper function to return the same type as fn.

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 calls
4.
const add = (a, b) => a + b;
5.
6.
// Wrap the function to enable call counting
7.
const countedAdd = count(add);
8.
9.
// Call the function a few times
10.
console.log("Count: ", countedAdd.getCount());; // 0
11.
12.
console.log("Sum: ", countedAdd(3, 5)); // 8
13.
console.log("Count: ", countedAdd.getCount()); // 1
14.
15.
console.log("Sum: ", countedAdd(2, 7));; // 9
16.
console.log("Count: ", countedAdd.getCount());; // 2
17.
18.
console.log("Sum: ", countedAdd(1, 4));; // 5
19.
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.