0

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.

  • Functions are immutable. You'll have to create a `spy()` function that returns a *new* function, and then call that instead of `fun()`. – Pointy Nov 09 '20 at 14:42
  • See the linked question's answers for details, but basically in ES5: `function spy(fun, callback) { return function() { try { callback.apply(this, arguments); } catch (e) { } return fun.apply(this, arguments); }; }` In ES2015+: `function spy(fun, callback) { return function(...args) { try { callback.apply(this, args); } catch (e) { } return fun.apply(this, args); }; }` In ES2020+, you can use just `} catch {` instead of `} catch(e) {`. – T.J. Crowder Nov 09 '20 at 14:45
  • @T.J.Crowder Thanks for your suggestion. – GNUSupporter 8964民主女神 地下教會 Nov 09 '20 at 16:18

0 Answers0