How to write a function spy(fun, callback)
which is an overloaded version of a function fun
in JavaScript, so that each time fun
is called, callback
is called?
For example, in the code below, each time Math.abs
is called, the console should print the line The ... called
twice.
function cb() {
console.log("The call back has been called");
}
Math.abs = spy(Math.abs, cb);
var result = Math.abs(-32);
result = Math.abs(-32);
console.log(result);
I found the following code on GitHub through code search, but the line The ... called
is printed once and only once no matter how many times Math.abs
are called.
function spy(fun, callback) {
if (typeof callback == 'function') {
callback(fun);
}
return fun;
}
I tried replacing callback(fun);
with callback();
, but it didn't help. I tried envelopping the code with an anonymous function.
function spy(fun, callback) {
return (typeof callback == 'function') ? () => {callback(); return fun} : fun;
}
This time the number of times that cb
is called is correct, but the return type is wrong.