Skip to content

Instantly share code, notes, and snippets.

@Drag13
Created September 20, 2018 18:55
Show Gist options
  • Save Drag13/850ed0eaeeeb210a465f4c2078c558c9 to your computer and use it in GitHub Desktop.
Save Drag13/850ed0eaeeeb210a465f4c2078c558c9 to your computer and use it in GitHub Desktop.
function spyFactory(array, prepushHandler, postpushHandler) {
const prepush = functionify(prepushHandler);
const postpush = functionify(postpushHandler);
const interceptor = {
get: function (obj, prop) {
if (prop !== 'push') { return obj[prop]; }
return function (...args) {
prepush(args);
Array.prototype.push.apply(this, args);
postpush(args);
}
}
}
function functionify(maybeNotAFunction) {
return typeof maybeNotAFunction === 'function' ? maybeNotAFunction : () => null;
}
return new Proxy(array, interceptor);
}
const spyedArray = spyFactory([77, 5], (arg) => { console.log(`prepush called with ${arg}`) });
spyedArray.push('4' );
console.log(spyedArray[2]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment