Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return the number of times a function is invoked?

Tags:

javascript

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 that can be called and behaves like argument
var count = 0;

var inner = function(){
  count++;
}

inner.callCount = function(){return count};

}

And this is how I'm testing it:

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

I feel like this is a simple problem that I should be able to simply google, but I haven't been able to find a solution. Thanks!

like image 417
Brayheart Avatar asked Oct 17 '22 23:10

Brayheart


1 Answers

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 ) );

//

function spyOn( fn, handler ) {
    
    let count = 0;
  
    return function inner ( ) {
        count++;
        const result = fn( ...arguments );
        handler( count, result );
        return result;
    };
    
}

function cube ( x ) {
    return x**3;
}
like image 66
Paul Avatar answered Oct 21 '22 06:10

Paul