Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Created March 2, 2020 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosePedroDias/2ffff6b701014a6d84cc4ff146e87af0 to your computer and use it in GitHub Desktop.
Save JosePedroDias/2ffff6b701014a6d84cc4ff146e87af0 to your computer and use it in GitHub Desktop.
spy and spyOnObject
function spy(fn, prot = fn.prototype) {
function proxy() {
const args = Array.prototype.slice.call(arguments);
proxy.calls.push(args);
proxy.called = true;
return fn.apply(this, args);
}
proxy.prototype = prot;
proxy.calls = [];
proxy.called = false;
return proxy;
}
function spyOnObject(o) {
const o2 = {};
for (let k in o) {
const v = o[k];
o2[k] = (typeof v === 'function') ? spy(v, o.prototype) : v;
}
return o2;
}
/// EXAMPLE USAGES:
/*
function soma(a, b) { return a + b; }
const soma2 = spy(soma);
console.log( soma2(2, 3) );
console.log( soma2(25, 11) );
*/
/*
const o = {
count: 0,
soma: function(a, b) { return a + b; },
add1: function() { return ++this.count; }
};
const o2 = spyOnObject(o);
o2.soma(2, 3);
o2.add1();
o2.add1();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment