count
returns the result of a function and the number of times that function is invoked.
1. Code
/**
* Invokes the function passed with arguments and
* counts how many times the function is executed.
*
* @param {Function} fn - The function to be called.
* @returns - result: the result of the passed function invocation.
* This function also has a getCount method attached.
* @returns {Function} getCount - A method that returns the count of execution of the passed function.
*/
const count = <A extends any[], R>(fn: (...args: A) => R) => {
let callCount = 0;
const wrapper = (...args: A): R => {
callCount++;
const result = fn(...args);
return result;
};
const getCount: () => number = () => callCount;
wrapper.getCount = getCount;
return wrapper;
};
export default count;
2. Installation
npx @jrtilak/lazykit@latest add count3. Description
The count function invokes another function passed as an arg and returns both the result of the invoked function and the count of how many times the function has been called.
This is useful in when you need to keep a tab on how many times a function is being called which can be helpful in monitoring, debugging, testing, analytics, resource management.
4. Props
Prop
Type
Default Value
function*Function---
5. Examples
import count from ".";
const add = (a: number, b: number) => {
return a + b;
};
const countAddFn = count(add);
countAddFn(1, 2);
countAddFn(3, 4);
console.log(countAddFn.getCount());
// Expected Output: 2