Created
February 22, 2018 08:07
-
-
Save whossname/c9dd268f7edd91637a5ce1694d08bb81 to your computer and use it in GitHub Desktop.
Function for outputting the difference from an expected object to the terminal in javascript. Useful for testing. Not the cleanest code I have written.
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 recursiveDiff(expected, actual, parentNodeStr) { | |
let isObject = expected !== null && typeof expected === 'object'; | |
isObject = isObject && (actual !== null && typeof actual === 'object'); | |
if (isObject) { | |
// eslint-disable-next-line no-restricted-syntax | |
for (const key in actual) { | |
if (Object.prototype.hasOwnProperty.call(actual, key)) { | |
const keyStr = `${parentNodeStr}.${key}`; | |
// eslint-disable-next-line no-prototype-builtins | |
if (actual.hasOwnProperty(key) && !expected.hasOwnProperty(key)) { | |
console.log(`expected does not have key: ${keyStr}`); | |
return; | |
} | |
const childIsObject = actual[key] !== null && typeof actual[key] === 'object'; | |
if (!childIsObject && actual[key] !== expected[key]) { | |
console.log(`actual value for key ${keyStr} is: ${actual[key].toString()}`); | |
} | |
recursiveDiff(expected[key], actual[key], keyStr); | |
} | |
} | |
} else if (Array.isArray(expected) && Array.isArray(actual)) { | |
if (actual.length !== expected.length) { | |
console.log('array are different lengths'); | |
return; | |
} | |
for (let i = 0; i < actual.length; i += 1) { | |
if (actual[i] !== expected[i]) { | |
console.log(`actual value for index ${i} is: ${actual[i]}`); | |
} else { | |
recursiveDiff(expected[i], actual[i], keyStr); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment