Skip to content

Instantly share code, notes, and snippets.

@re5et
Forked from davidmfoley/gist:3041435
Created July 3, 2012 18:23
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 re5et/3041583 to your computer and use it in GitHub Desktop.
Save re5et/3041583 to your computer and use it in GitHub Desktop.
Object Before / After differ.
var Differ = function(obj){
this.obj = obj;
};
Differ.prototype.cacheVars = function(){
this.cache = {};
for(var prop in this.obj){
this.cache[prop] = this.obj[prop];
}
};
Differ.prototype.diff = function(){
for(var prop in this.obj){
// it is the same
if(this.obj[prop] === this.cache[prop]){
continue;
}
else{
// it has changed
if(this.cache[prop] && this.obj[prop] !== this.cache[prop]){
console.log(prop+' changed from: '+this.cache[prop]+' to: '+this.obj[prop] + '!');
}
else{
// it is new
if(this.obj[prop] && !this.cache[prop]){
console.log(prop+' was introduced! Value is: '+this.obj[prop]);
}
}
}
}
// check for deleted properties
for(var prop in this.cache){
// it was deleted
if(this.cache[prop] !== undefined && this.obj[prop] === undefined){
console.log(prop+' was deleted!');
}
}
};
// Use like:
//
var myDiffer = new Differ(window);
window.foo = 'bar'
window.bar = 'baz'
myDiffer.cacheVars();
window.qux = 1;
window.foo = function(){console.log('baz')};
delete window.bar;
myDiffer.diff();
@re5et
Copy link
Author

re5et commented Jul 3, 2012

use obj instead of thing, replaced a few missing window / obj references,

@re5et
Copy link
Author

re5et commented Jul 3, 2012

wish i could come up with a better short name for what this thing does.

@nocash
Copy link

nocash commented Jul 3, 2012

Delta? I think I prefer Differ/diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment