//
you're reading...
Programming

Calculating Object Difference in JavaScript

// ECMA 5+
    function objectDifference(obj1, obj2) {
        var hashArr1 = [],
            hashArr2 = [];
        var keys1 = Object.keys(obj1);
        for(var i = 0; i < keys1.length; i++) {
            hashArr1[keys1[i].hashCode()] = obj1[keys1[i]];
        }
        var keys2 = Object.keys(obj2);
        for(var i = 0; i < keys2.length; i++) {
            hashArr2[keys2[i].hashCode()] = obj2[keys2[i]];
        }
        var diff = _.difference(hashArr1, hashArr2);
    };

    String.prototype.hashCode = function() {
        var hash = 0, i, chr, len;
        if (this.length == 0) return hash;
        for (i = 0, len = this.length; i < len; i++) {
            chr   = this.charCodeAt(i);
            hash  = ((hash << 5) - hash) + chr;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
    };
Advertisements

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: