Created
May 12, 2014 16:29
-
-
Save sclarson/6639df4d9a306e1413db to your computer and use it in GitHub Desktop.
Modified deep compare of JS objects... definitely not as nice as the way clojurescript handle mutation...
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
function findDifferences(objectA, objectB, onlyOwnProperties) { | |
var propertyChanges = []; | |
var objectGraphPath = ["this"]; | |
(function(a, b) { | |
if (a.constructor == Array) { | |
// BIG assumptions here: That both arrays are same length, that | |
// the members of those arrays are _essentially_ the same, and | |
// that those array members are in the same order... | |
for (var i = 0; i < a.length; i++) { | |
objectGraphPath.push("[" + i.toString() + "]"); | |
arguments.callee(a[i], b[i]); | |
objectGraphPath.pop(); | |
} | |
} else if (a.constructor == Object || (a.constructor != Number && | |
a.constructor != String && a.constructor != Date && | |
a.constructor != RegExp && a.constructor != Function && | |
a.constructor != Boolean)) { | |
// we can safely assume that the objects have the | |
// same property lists, else why compare them? | |
for (var property in a) { | |
objectGraphPath.push(("." + property)); | |
if (a[property] == null || b[property] == null || | |
a[property] == undefined || b[property] == undefined || | |
a[property].constructor == null || a[property].constructor == undefined || | |
b[property].constructor == null || b[property].constructor == undefined) { | |
if (a[property] != b[property]) { | |
propertyChanges.push({ "Property": objectGraphPath.join(""), "ObjectA": a, "ObjectB": b }); | |
} | |
continue; | |
} | |
if (a[property].constructor != Function) { | |
if (onlyOwnProperties != undefined && onlyOwnProperties == true && a.hasOwnProperty(property)) { | |
arguments.callee(a[property], b[property]); | |
} else { | |
arguments.callee(a[property], b[property]); | |
} | |
} | |
objectGraphPath.pop(); | |
} | |
} else if (a.constructor != Function) { // filter out functions | |
if (a.constructor == Date) { | |
if (+a != +b) { | |
propertyChanges.push({ "Property": objectGraphPath.join(""), "ObjectA": a, "ObjectB": b }); | |
} | |
} else if (a != b) { | |
propertyChanges.push({ "Property": objectGraphPath.join(""), "ObjectA": a, "ObjectB": b }); | |
} | |
} | |
})(objectA, objectB); | |
return propertyChanges; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment