Skip to content

Instantly share code, notes, and snippets.

@dmcblue
Last active September 3, 2021 18:15
Show Gist options
  • Save dmcblue/143d3d7a53eab9e2a912e4ce35b4f3d4 to your computer and use it in GitHub Desktop.
Save dmcblue/143d3d7a53eab9e2a912e4ce35b4f3d4 to your computer and use it in GitHub Desktop.
Javascript Compare
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