Created
December 15, 2017 00:47
-
-
Save messerc/7124496f8398708edd6a4f6343aa98c5 to your computer and use it in GitHub Desktop.
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
/** | |
* Write a function that, given two objects, returns whether or not the two | |
* are deeply equivalent--meaning the structure of the two objects is the | |
* same, and so is the structure of each of their corresponding descendants. | |
* | |
* Examples: | |
* | |
* deepEquals({a:1, b: {c:3}},{a:1, b: {c:3}}); // true | |
* deepEquals({a:1, b: {c:5}},{a:1, b: {c:6}}); // false | |
* | |
* don't worry about handling cyclical object structures. | |
* | |
NOTE: if your interviewee immediately jumps to a JSON.stringify-based solution, acknowledge that it is a | |
naive & valid implementation but add it as a constraint to NOT use it for their solution. | |
*/ | |
// Solution | |
var deepEquals = function(apple, orange) { | |
if (apple === orange) { return true; } | |
if (apple && !orange || !apple && orange) { return false; } | |
if (!(apple instanceof Object) || !(orange instanceof Object)) { return false; } | |
var appleKeys = Object.keys(apple); | |
var orangeKeys = Object.keys(orange); | |
if (appleKeys.length !== orangeKeys.length) { return false; } | |
if (appleKeys.length === 0) { return true; } // two empty objects are equal | |
for (var i = 0; i < appleKeys.length; i++) { | |
if (!deepEquals(apple[appleKeys[i]], orange[appleKeys[i]])) { return false; } | |
} | |
return true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment