Created
November 24, 2017 19:44
-
-
Save dgendill/a25e10dce4753b1b40c9750a7e48d47d to your computer and use it in GitHub Desktop.
JavaScript Object Diff
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
// Some initial work on an object differ. | |
var difference = Delta( | |
{ | |
a:{m:1}, | |
c:22 | |
}, | |
{ | |
a:{n:1}, | |
b:7 | |
} | |
); | |
console.log(JSON.stringify(difference)); | |
/* | |
{ | |
"deltas":[ | |
{ | |
"type":"NestedDelta", | |
"prop":"a", | |
"deltas":[ | |
{"type":"RemoveProp","prop":"m"}, | |
{"type":"AddProp","prop":"n","value":1} | |
] | |
}, | |
{"type":"RemoveProp","prop":"c"}, | |
{"type":"AddProp","prop":"b","value":7} | |
] | |
} | |
*/ | |
function NDelta(prop, delta) { | |
if (!(this instanceof NDelta)) { return new NDelta(prop, delta); } | |
this.type = "NestedDelta"; | |
this.prop = prop; | |
this.deltas = delta.deltas; | |
} | |
function Remove(prop) { | |
if (!(this instanceof Remove)) { return new Remove(prop); } | |
this.type = "RemoveProp"; | |
this.prop = prop; | |
} | |
function Change(prop, from, to) { | |
if (!(this instanceof Change)) { return new Change(prop, from, to); } | |
this.type = "ChangeProp"; | |
this.prop = prop; | |
this.from = from; | |
this.to = to; | |
} | |
Change.prototype.toString = function() { | |
return "Change '" + this.prop + "' from " + this.v1 + " to " + this.v2; | |
} | |
function Add(prop, value) { | |
if (!(this instanceof Add)) { return new Add(prop, value); } | |
this.type = "AddProp"; | |
this.prop = prop; | |
this.value = value; | |
} | |
function Delta(o1, o2) { | |
if (!(this instanceof Delta)) { return new Delta(o1, o2); } | |
var deltas = []; | |
var o2Skip = {}; | |
var i; | |
for (i in o1) { | |
if (o1.hasOwnProperty(i)) { | |
if (!o2.hasOwnProperty(i)) { | |
deltas.push(Remove(i)); | |
continue; | |
} else { | |
o2Skip[i] = true; | |
} | |
if (o1[i] === o2[i]) { | |
continue; | |
} | |
if (typeof o1[i] == 'object') { | |
deltas.push.call(deltas, NDelta(i, Delta(o1[i], o2[i]))); | |
continue; | |
} | |
if (o1[i] !== o2[i]) { | |
deltas.push(Change(i, o1[i], o2[i])); | |
} | |
} | |
} | |
for(i in o2) { | |
if (o2Skip[i]) continue; | |
if (o2.hasOwnProperty(i)) { | |
deltas.push(Add(i, o2[i])); | |
} | |
} | |
this.deltas = deltas; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment