Please login or register. Welcome to the Studio, guest!


Quick Links:


newBookmarkLockedFalling

Aaron

Aaron Avatar
Bad Wolf

****
Dedicated Studio Member

859


November 2006
This is pretty much the heart of a few of my snippets. You can apply it to any object, not just nodes. Keep in mind though that it doesn't discriminate datatypes. It'll look at 2 != "2" and return false. Just change the operation to fix this.

Description: Compares the properties/methods/objects of two objects and returns true if they are alike.

Syntax: correlate(object, comparison object)

function correlate(a, b) {
for(var x in b) {
if(!a[x] && !b[x])
continue;
if(!a[x] && b[x] || a[x] && !b[x])
return false;
else if(a[x] && b[x].constructor == Object) {
if(!correlate(a[x], b[x]))
return false;
} else if((b[x].constructor == RegExp ? !a[x].match(b[x]) : a[x].toString() != b[x].toString()))
return false;
}
return true;
}


Example:

var i = document.body;
correlate(i, { nodeName: "BODY" })
// true, objects have same nodeName property
correlate({ nodeName: "BODY" }, i)
// false, first object lacks properties, methods, and/or objects of document.body

correlate(new Array("L"), new Array("K")) // false
correlate({ name: "dErfleurer", age: 16 }, { name: /der/i }) // true





Last Edit: Jun 16, 2007 19:09:47 GMT by Aaron

Aaron

Aaron Avatar
Bad Wolf

****
Dedicated Studio Member

859


November 2006
Just an update to the previous snippet. Some performance enhancements and the ability to recognize unique boolean false values like 0, undefined, and null.

function correlate(a, b) {
       for(var x in b) {
               var c = a[x], d = b[x];
               if(!c && !d && c === d)
                       continue;
               if(c && d) {
                       if(typeof c == typeof d) {
                               if(typeof c == "object") {
                                       if(correlate(c, d))
                                               continue;
                               } else if(c.toString() == d.toString())
                                       continue;
                       } else if(d.constructor == RegExp && d.test(c.toString()))
                               continue;
               }
               return false;
       }
       return true;
}


newBookmarkLockedFalling