How to return the number of times a function is called?

I am trying to return a value after a function has been called n times. Here is what I still have:

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 here is how I test it:

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

I feel that this is a simple problem that I should be able to just google, but I could not find a solution. Thanks!

+5
source share
2 answers

It looks like your spyOn function should take the fn function as an argument and return a function (its inner is called), calling fn with inner arguments, with the value 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; } 
+2
source

You can do something like an interceptor of your function :

This is a tiny version, now you can add arguments and necessary behavior, the most important thing here is how your function was wrapped by an interceptor, and each call will increase the number of calls.

 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(); } 
+1
source

Source: https://habr.com/ru/post/1274973/


All Articles