Last active
September 3, 2021 18:15
-
-
Save dmcblue/143d3d7a53eab9e2a912e4ce35b4f3d4 to your computer and use it in GitHub Desktop.
Javascript Compare
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
function isObject(v) { | |
return typeof v === 'object' && v !== null | |
} | |
function compare(a, b, indent) { | |
var toplevel = false; | |
if (indent === undefined) { | |
indent = 0; | |
toplevel = true; | |
} | |
var log = []; | |
var tab = (new Array(indent)).fill('-').join(''); | |
if(Array.isArray(a) && Array.isArray(b)) { | |
a.forEach(function(key) { | |
if(b.indexOf(key) === -1) { | |
log.push(`${tab}Item '${key}' in A but not in B`); | |
} | |
}); | |
b.forEach(function(key) { | |
if(a.indexOf(key) === -1) { | |
log.push(`${tab}Item '${key}' in B but not in A`); | |
} | |
}); | |
} else if(isObject(a) && isObject(b)){ | |
var aKeys = Object.keys(a); | |
var bKeys = Object.keys(b); | |
aKeys.forEach(function(key) { | |
if(bKeys.indexOf(key) === -1) { | |
log.push(`${tab}Key '${key}' in A but not in B`); | |
} | |
}); | |
bKeys.forEach(function(key) { | |
if(aKeys.indexOf(key) === -1) { | |
log.push(`${tab}Key '${key}' in B but not in A`); | |
} | |
}); | |
aKeys.forEach(function(key) { | |
if(bKeys.indexOf(key) !== -1) { | |
var childLogs = compare(a[key], b[key], indent + 1); | |
if(childLogs.length) { | |
log.push(`${tab}Key '${key}':`); | |
log = log.concat(childLogs); | |
} | |
} | |
}); | |
} else if (a !== b) { | |
log.push(a); | |
log.push(b); | |
} | |
if(toplevel) { | |
console.log(log.join("\n")); | |
} | |
return log; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment