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!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With