Last active
August 29, 2015 14:11
-
-
Save atomkirk/10d482541d0a64e806a2 to your computer and use it in GitHub Desktop.
unordered javascript object isEqual
This file contains 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
// compares two objects deeply ignoring array ordering. | |
isEqual = function(a, b) { | |
objectMap = function(obj) { | |
var map = []; | |
var queue = [{ key: '', value: obj }]; | |
while (queue.length > 0) { | |
var current = queue.shift(); | |
var key = current.key; | |
var value = current.value; | |
var scope = current.scope; | |
if (Ember.typeOf(value) == 'array') { | |
for (i = 0; i < value.length; i++) { | |
var v = value[i]; | |
var newKey = key + '.' + '[' + (scope != undefined ? scope : '') + ']'; | |
queue.push({ key: newKey, value: v, scope: i }); | |
} | |
} | |
else if (Ember.typeOf(value) == 'object') { | |
for (prop in value) { | |
var v = value[prop]; | |
var newKey = key + '.' + prop; | |
queue.push({ key: newKey, value: v, scope: scope }) | |
} | |
} | |
else { | |
map.push(key + '=' + value); | |
} | |
} | |
return map; | |
} | |
aMap = objectMap(a).sort().join(","); | |
bMap = objectMap(b).sort().join(","); | |
return aMap == bMap; | |
}; | |
isEqual("a", "a"); // true | |
isEqual( { a: [1,2,3] }, { a: [1,2,3] } ); // true | |
isEqual( { a: [1,2,3] }, { a: [1,3,2] } ); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment