Created
November 5, 2015 23:10
-
-
Save skeggse/1af4eeeb74fbe38cba73 to your computer and use it in GitHub Desktop.
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
var hasOwn = Object.prototype.hasOwnProperty; | |
var indexOf = Array.prototype.indexOf; | |
function isObjectEmpty(obj) { | |
for (var key in obj) { | |
return false; | |
} | |
return true; | |
} | |
function copyKeys(obj) { | |
var newObj = {}; | |
for (var key in obj) { | |
newObj[key] = undefined; | |
} | |
return newObj; | |
} | |
// compares the structure of JSON-compatible, non-circular values | |
function compareStructure(a, b) { | |
if (typeof a !== typeof b) { | |
return false; | |
} | |
if (typeof a === 'object') { | |
// both or neither, but not mismatched | |
if (Array.isArray(a) !== Array.isArray(b)) { | |
return false; | |
} | |
if (Array.isArray(a)) { | |
// can't compare structure in array if we don't have items in both | |
if (!a.length || !b.length) { | |
return true; | |
} | |
for (var i = 1; i < a.length; i++) { | |
if (!compareStructure(a[0], a[i])) { | |
return false; | |
} | |
} | |
for (var i = 0; i < b.length; i++) { | |
if (!compareStructure(a[0], b[i])) { | |
return false; | |
} | |
} | |
return true; | |
} | |
var map = copyKeys(a), keys = Object.keys(b); | |
for (var i = 0; i < keys.length; i++) { | |
var key = keys[i]; | |
if (!hasOwn.call(map, key) || !compareStructure(a[key], b[key])) { | |
return false; | |
} | |
delete map[key]; | |
} | |
// we should've found all the keys in the map | |
return isObjectEmpty(map); | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment