Last active
December 21, 2015 01:59
-
-
Save TyOverby/6232169 to your computer and use it in GitHub Desktop.
Wraps an object and records all calls and property accesses and property modifications through that object.
This file contains hidden or 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
| var Record = (function () { | |
| function Record(inner) { | |
| this.__inner = inner; | |
| this.__history = []; | |
| var _this = this; | |
| var wrapFunction = function (funcName) { | |
| this[funcName] = function () { | |
| var args = Array.prototype.slice.call(arguments); | |
| // Should we bind to 'this' or __inner? | |
| var result = this.__inner[funcName].apply(this, args); | |
| this.__history.push({ | |
| 'type': 'function-call', | |
| 'name': funcName, | |
| 'args': args, | |
| 'result': result, | |
| 'reapply': function (){ | |
| this.__inner[funcName].apply(this, args); | |
| } | |
| }); | |
| return result; | |
| }; | |
| }; | |
| var wrapProperty = function (propName) { | |
| this.__defineGetter__(propName, function () { | |
| var result = this.__inner[propName]; | |
| this.__history.push({ | |
| 'type': 'property-getter', | |
| 'name': propName, | |
| 'result': result, | |
| 'reapply': function () { | |
| return result; | |
| } | |
| }); | |
| return result; | |
| }); | |
| this.__defineSetter__(propName, function(val){ | |
| this.__history.push({ | |
| 'type': 'property-setter', | |
| 'name': propName, | |
| 'old-value': this.__inner[propName], | |
| 'new-value': val, | |
| 'reapply': function () { | |
| return this.__inner[propName] = val; | |
| } | |
| }); | |
| this.__inner[propName] = val; | |
| }); | |
| }; | |
| for(key in this.__inner) { | |
| console.log(key); | |
| if(typeof this.__inner[key] === 'function') { | |
| wrapFunction.bind(this)(key); | |
| } else { | |
| wrapProperty.bind(this)(key); | |
| } | |
| } | |
| } | |
| return Record; | |
| })(); | |
| module.exports = Record; |
This file contains hidden or 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
| var Record = require('./history'); | |
| var myObj = { | |
| sayA: function () { | |
| console.log('a'); | |
| }, | |
| say: function (what) { | |
| console.log(what); | |
| } | |
| }; | |
| var recorded = new Record(myObj); | |
| console.log(recorded); | |
| recorded.sayA(); | |
| recorded.sayA(); | |
| recorded.say('hi'); | |
| console.log(recorded.__history) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment