user242007
user242007

Reputation: 286

Object comparison function, do not understand this example

The example below is taken from an exercise at the end of Chapter 4 of Eloquent Javascript.

function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

Most of this function is easy enough for me to understand, but there's one part where I'm not really sure what's going on:

 for (var prop in b) {
        propsInB += 1;
        if (!(prop in a) || !deepEqual(a[prop], b[prop]))
          return false;
}

A for loop iterates through the properties in the provided object, "b", incrementing up the value of propsInB each time, and then I don't really follow why the if statement's conditions are what they are.

I'd appreciate any explanation.

Upvotes: 2

Views: 175

Answers (2)

webdeb
webdeb

Reputation: 13211

Ok, lets analyze them..

for (var prop in b) {
    propsInB += 1; // Increment to 
    if ( 
          !(prop in a) ||  // exists in a???
          !deepEqual(a[prop], b[prop])) // !! -> this is the point where recursion is happaning
      return false;
}

This checks if the property exists in a too.

   !(prop in a)  

this is the point where recursion is happening..

!deepEqual(a[prop], b[prop]))

Imagine recursion like you looking for the deepest document in a folder structure: /home/me/stuff/cool-stuff/games/..

you don't know the structure, but you have to find the deepest document, you will do it with recursion.

pseudo code:

  goDeeper(folder) {
    childFolders = findAllFolderInFolder(folder);
    if (!childFolders) {
      alert('found the deepest Folder: ' + folder);
      return;
    } else
      childFolders.forEach(goDeeper); // Call goDeeper for each folder in this folder...
  }

  goDeeper('/'); // It will go through all the filesystem, and each time it finds an end it will alert('...');

So this pseudo code would walk into each folder and try to go deeper and deeper..

Upvotes: 1

Pointy
Pointy

Reputation: 413712

It's checking to make sure that the property it's found in b is also a property in a, and that the values of both properties are the same.

So, if a has properties "x" and "y", but b has properties "y" and "z", the test will fail for property "z", and it will fail for property "y" if a.y and b.y are not "deep equal".

Upvotes: 1

Related Questions