Skip to content

Instantly share code, notes, and snippets.

@TyOverby
Last active December 21, 2015 01:59
Show Gist options
  • Select an option

  • Save TyOverby/6232169 to your computer and use it in GitHub Desktop.

Select an option

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.
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;
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