Guest User

Untitled

a guest
Dec 17th, 2017
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. /**
  2. * Write a function that, given two objects, returns whether or not the two
  3. * are deeply equivalent--meaning the structure of the two objects is the
  4. * same, and so is the structure of each of their corresponding descendants.
  5. *
  6. * Examples:
  7. *
  8. * deepEquals({a:1, b: {c:3}},{a:1, b: {c:3}}); // true
  9. * deepEquals({a:1, b: {c:5}},{a:1, b: {c:6}}); // false
  10. *
  11. * don't worry about handling cyclical object structures.
  12. *
  13.  
  14. NOTE: if your interviewee immediately jumps to a JSON.stringify-based solution, acknowledge that it is a
  15. naive & valid implementation but add it as a constraint to NOT use it for their solution.
  16. */
  17.  
  18. // Solution
  19.  
  20. var deepEquals = function(apple, orange) {
  21.  
  22. if (apple === orange) { return true; }
  23. if (apple && !orange || !apple && orange) { return false; }
  24. if (!(apple instanceof Object) || !(orange instanceof Object)) { return false; }
  25. var appleKeys = Object.keys(apple);
  26. var orangeKeys = Object.keys(orange);
  27. if (appleKeys.length !== orangeKeys.length) { return false; }
  28. if (appleKeys.length === 0) { return true; } // two empty objects are equal
  29. for (var i = 0; i < appleKeys.length; i++) {
  30. if (!deepEquals(apple[appleKeys[i]], orange[appleKeys[i]])) { return false; }
  31. }
  32. return true;
  33. };
Add Comment
Please, Sign In to add comment