mardi 8 septembre 2015

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.

Aucun commentaire:

Enregistrer un commentaire