count

returns the result of a function and the number of times that function is invoked.

1. Code

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 count

3. 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