Skip to content

Instantly share code, notes, and snippets.

@janetlee
Forked from messerc/deepEquality.js
Created December 15, 2017 17:19
Show Gist options
  • Save janetlee/a23651a3ee2b607e67eb3f038fa3610d to your computer and use it in GitHub Desktop.
Save janetlee/a23651a3ee2b607e67eb3f038fa3610d to your computer and use it in GitHub Desktop.

Revisions

  1. @messerc messerc created this gist Dec 15, 2017.
    33 changes: 33 additions & 0 deletions deepEquality.js
    Original 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;
    };