Brayheart
Brayheart

Reputation: 167

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 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!

Upvotes: 5

Views: 866

Answers (2)

Ele
Ele

Reputation: 33726

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.

function spyOn(fn) {
  var count = 0;
  
  return function() {
    fn();
    count++;

    console.log(count);
  }
}

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

var spy = spyOn(myFunction);

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

Upvotes: 1

Paul
Paul

Reputation: 141877

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

Upvotes: 2

Related Questions