count

Calls a function and returns result and the times the funciton is called.

1. Code

/***
 *  Invokes the function passed with args and counts how many times the function is excueted.
 * 
 *  @param {fn:Function} - The function to be called.
 *  @returns - A new function that excutes the given function and returns the result.
 *  @returns {getCount:Function} - A method that returns the count of exceution of the passed function. 
 ***/





const count = <T>(fn: (...args: any[]) => T) => {
  let callCount = 0;

  const wrapper= (...args: any[]): T  => {
    callCount++;
    console.log(`Original function called ${callCount} times`);
    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 -undefined

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.

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);
// Expected Output: Original function called 1 times
countAddFn(3,4);
// Expected Output: Original function called 2 times
console.log(countAddFn.getCount());
// Expected Output: 2