A deep equals implementation that can also work with cycles and works efficiently with references - Node.js Object

Node.js examples for Object:Equal

Description

A deep equals implementation that can also work with cycles and works efficiently with references

Demo Code

 
/**//from  w w w .  j  a va2 s  .com
 * a deep equals implementation that can also work with cycles and works
 * efficiently with references
 */
function equals(a, b) {
  var eqa = [];
  var eqb = [];
  function deepEqual(a, b) {
    if (a === b)
      return true;
    else if (typeof a !== typeof b)
      return false;
    else if (typeof a === 'object' && a !== null) {
      var indexA = eqa.indexOf(a);
      if (indexA !== -1 && indexA === eqb.indexOf(b))
        return true; // just assume true if we find a cycle
      eqa.push(a);
      eqb.push(b);
      var pa = Object.getPrototypeOf(a);
      var pb = Object.getPrototypeOf(b);
      if (pa !== pb)
        return false;
      var ka = Object.keys(a).sort();
      var kb = Object.keys(b).sort();
      if (ka.length !== kb.length)
        return false;
      for (var i = 0; i < ka.length; i++) {
        if (ka[i] !== kb[i])
          return false;
        var k = ka[i];
        if (!deepEqual(a[k], b[k]))
          return false;
      }
      return true; // no props -> equal
    } else
      return false; // dont care about anything other than primitives and objects
  }
  return deepEqual(a, b);
}

Related Tutorials