Skip to content Skip to sidebar Skip to footer

How Do I Return The Number Of Times A Function Is Invoked?

I'm trying to return a value after a function has been invoked n number of times. Here's what I have so far: function spyOn(fn) { //takes in function as argument //returns function

Solution 1:

It looks like your spyOn function should accept a function fn as an argument and return a function (lets call it inner) that calls fn with the arguments inner is called with and returns the value the fn returns:

const spiedCube = spyOn( cube, function ( count, result ) {
  if ( count % 3 === 0 )
    console.log( `Called ${count} times. Result: ${result}` );
} );

for ( let i = 0; i < 12; i++ )
  console.log( spiedCube( i ) );

//functionspyOn( fn, handler ) {
    
    let count = 0;
  
    returnfunctioninner ( ) {
        count++;
        const result = fn( ...arguments );
        handler( count, result );
        return result;
    };
    
}

functioncube ( x ) {
    return x**3;
}

Solution 2:

You can do something like an interceptor of your function:

This is a tiny version, from now you can add the arguments and necessary behavior, the most important here it's how your function was wrapped by an interceptor and every call will increment a count of invocations.

functionspyOn(fn) {
  var count = 0;
  
  returnfunction() {
    fn();
    count++;

    console.log(count);
  }
}

var myFunction = function() {
  console.log("called!");
};

var spy = spyOn(myFunction);

for (var i = 0; i < 99; i++) {
  spy();
}

Post a Comment for "How Do I Return The Number Of Times A Function Is Invoked?"