Created
September 20, 2018 18:55
-
-
Save Drag13/850ed0eaeeeb210a465f4c2078c558c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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