-
-
Save janetlee/a23651a3ee2b607e67eb3f038fa3610d to your computer and use it in GitHub Desktop.
Revisions
-
messerc created this gist
Dec 15, 2017 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,33 @@ /** * 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; };