recursively extending and merging javascript objects - javascript

I have written two methods for extending and merging javascript objects. It might be bad question, but I'm not sure that I'm doing it right. Can you look at code and tell if I need something to improve and if i'm doing something wrong (code works at the first glance)
merge: function (a, b) {
var copy = {};
CL.extend(copy, a, [HTMLElement, Array]);
CL.extend(copy, b, [HTMLElement, Array]);
return copy;
},
extend: function extend(a, b, excludeInstances) {
for (var prop in b)
if (b.hasOwnProperty(prop)) {
var isInstanceOfExcluded = false;
if (excludeInstances)
for (var i = 0; i < excludeInstances.length; i++)
if (b[prop] instanceof excludeInstances[i])
isInstanceOfExcluded = true;
if (typeof b[prop] === 'object' && !isInstanceOfExcluded) {
a[prop] = a[prop] !== undefined ? a[prop] : {};
extend(a[prop], b[prop], excludeInstances);
} else
a[prop] = b[prop];
}
}

Related

Why i can't compare two objects in javascript? [duplicate]

This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Closed 6 years ago.
What is the best way to compare objects in JavaScript?
Example:
var user1 = {name : "nerd", org: "dev"};
var user2 = {name : "nerd", org: "dev"};
var eq = user1 == user2;
alert(eq); // gives false
I know that two objects are equal if they refer to the exact same object, but is there a way to check if they have the same attributes' values?
The following way works for me, but is it the only possibility?
var eq = Object.toJSON(user1) == Object.toJSON(user2);
alert(eq); // gives true
Unfortunately there is no perfect way, unless you use _proto_ recursively and access all non-enumerable properties, but this works in Firefox only.
So the best I can do is to guess usage scenarios.
1) Fast and limited.
Works when you have simple JSON-style objects without methods and DOM nodes inside:
JSON.stringify(obj1) === JSON.stringify(obj2)
The ORDER of the properties IS IMPORTANT, so this method will return false for following objects:
x = {a: 1, b: 2};
y = {b: 2, a: 1};
2) Slow and more generic.
Compares objects without digging into prototypes, then compares properties' projections recursively, and also compares constructors.
This is almost correct algorithm:
function deepCompare () {
var i, l, leftChain, rightChain;
function compare2Objects (x, y) {
var p;
// remember that NaN === NaN returns false
// and isNaN(undefined) returns true
if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
return true;
}
// Compare primitives and functions.
// Check if both arguments link to the same object.
// Especially useful on the step where we compare prototypes
if (x === y) {
return true;
}
// Works in case when functions are created in constructor.
// Comparing dates is a common scenario. Another built-ins?
// We can even handle functions passed across iframes
if ((typeof x === 'function' && typeof y === 'function') ||
(x instanceof Date && y instanceof Date) ||
(x instanceof RegExp && y instanceof RegExp) ||
(x instanceof String && y instanceof String) ||
(x instanceof Number && y instanceof Number)) {
return x.toString() === y.toString();
}
// At last checking prototypes as good as we can
if (!(x instanceof Object && y instanceof Object)) {
return false;
}
if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
return false;
}
if (x.constructor !== y.constructor) {
return false;
}
if (x.prototype !== y.prototype) {
return false;
}
// Check for infinitive linking loops
if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
return false;
}
// Quick checking of one object being a subset of another.
// todo: cache the structure of arguments[0] for performance
for (p in y) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
}
else if (typeof y[p] !== typeof x[p]) {
return false;
}
}
for (p in x) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
}
else if (typeof y[p] !== typeof x[p]) {
return false;
}
switch (typeof (x[p])) {
case 'object':
case 'function':
leftChain.push(x);
rightChain.push(y);
if (!compare2Objects (x[p], y[p])) {
return false;
}
leftChain.pop();
rightChain.pop();
break;
default:
if (x[p] !== y[p]) {
return false;
}
break;
}
}
return true;
}
if (arguments.length < 1) {
return true; //Die silently? Don't know how to handle such case, please help...
// throw "Need two or more arguments to compare";
}
for (i = 1, l = arguments.length; i < l; i++) {
leftChain = []; //Todo: this can be cached
rightChain = [];
if (!compare2Objects(arguments[0], arguments[i])) {
return false;
}
}
return true;
}
Known issues (well, they have very low priority, probably you'll never notice them):
objects with different prototype structure but same projection
functions may have identical text but refer to different closures
Tests: passes tests are from How to determine equality for two JavaScript objects?.
Here is my ES3 commented solution (gory details after the code):
function object_equals( x, y ) {
if ( x === y ) return true;
// if both x and y are null or undefined and exactly the same
if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
// if they are not strictly equal, they both need to be Objects
if ( x.constructor !== y.constructor ) return false;
// they must have the exact same prototype chain, the closest we can do is
// test there constructor.
for ( var p in x ) {
if ( ! x.hasOwnProperty( p ) ) continue;
// other properties were tested using x.constructor === y.constructor
if ( ! y.hasOwnProperty( p ) ) return false;
// allows to compare x[ p ] and y[ p ] when set to undefined
if ( x[ p ] === y[ p ] ) continue;
// if they have the same strict value or identity then they are equal
if ( typeof( x[ p ] ) !== "object" ) return false;
// Numbers, Strings, Functions, Booleans must be strictly equal
if ( ! object_equals( x[ p ], y[ p ] ) ) return false;
// Objects and Arrays must be tested recursively
}
for ( p in y )
if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) )
return false;
// allows x[ p ] to be set to undefined
return true;
}
In developing this solution, I took a particular look at corner cases, efficiency, yet trying to yield a simple solution that works, hopefully with some elegance. JavaScript allows both null and undefined properties and objects have prototypes chains that can lead to very different behaviors if not checked.
First I have chosen to not extend Object.prototype, mostly because null could not be one of the objects of the comparison and that I believe that null should be a valid object to compare with another. There are also other legitimate concerns noted by others regarding the extension of Object.prototype regarding possible side effects on other's code.
Special care must taken to deal the possibility that JavaScript allows object properties can be set to undefined, i.e. there exists properties which values are set to undefined. The above solution verifies that both objects have the same properties set to undefined to report equality. This can only be accomplished by checking the existence of properties using Object.hasOwnProperty( property_name ). Also note that JSON.stringify() removes properties that are set to undefined, and that therefore comparisons using this form will ignore properties set to the value undefined.
Functions should be considered equal only if they share the same reference, not just the same code, because this would not take into account these functions prototype. So comparing the code string does not work to guaranty that they have the same prototype object.
The two objects should have the same prototype chain, not just the same properties. This can only be tested cross-browser by comparing the constructor of both objects for strict equality. ECMAScript 5 would allow to test their actual prototype using Object.getPrototypeOf(). Some web browsers also offer a __proto__ property that does the same thing. A possible improvement of the above code would allow to use one of these methods whenever available.
The use of strict comparisons is paramount here because 2 should not be considered equal to "2.0000", nor false should be considered equal to null, undefined, or 0.
Efficiency considerations lead me to compare for equality of properties as soon as possible. Then, only if that failed, look for the typeof these properties. The speed boost could be significant on large objects with lots of scalar properties.
No more that two loops are required, the first to check properties from the left object, the second to check properties from the right and verify only existence (not value), to catch these properties which are defined with the undefined value.
Overall this code handles most corner cases in only 16 lines of code (without comments).
Update (8/13/2015). I have implemented a better version, as the function value_equals() that is faster, handles properly corner cases such as NaN and 0 different than -0, optionally enforcing objects' properties order and testing for cyclic references, backed by more than 100 automated tests as part of the Toubkal project test suite.
Utils.compareObjects = function(o1, o2){
for(var p in o1){
if(o1.hasOwnProperty(p)){
if(o1[p] !== o2[p]){
return false;
}
}
}
for(var p in o2){
if(o2.hasOwnProperty(p)){
if(o1[p] !== o2[p]){
return false;
}
}
}
return true;
};
Simple way to compare ONE-LEVEL only objects.
Certainly not the only way - you could prototype a method (against Object here but I certainly wouldn't suggest using Object for live code) to replicate C#/Java style comparison methods.
Edit, since a general example seems to be expected:
Object.prototype.equals = function(x)
{
for(p in this)
{
switch(typeof(this[p]))
{
case 'object':
if (!this[p].equals(x[p])) { return false }; break;
case 'function':
if (typeof(x[p])=='undefined' || (p != 'equals' && this[p].toString() != x[p].toString())) { return false; }; break;
default:
if (this[p] != x[p]) { return false; }
}
}
for(p in x)
{
if(typeof(this[p])=='undefined') {return false;}
}
return true;
}
Note that testing methods with toString() is absolutely not good enough but a method which would be acceptable is very hard because of the problem of whitespace having meaning or not, never mind synonym methods and methods producing the same result with different implementations. And the problems of prototyping against Object in general.
The following algorithm will deal with self-referential data structures, numbers, strings, dates, and of course plain nested javascript objects:
Objects are considered equivalent when
They are exactly equal per === (String and Number are unwrapped first to ensure 42 is equivalent to Number(42))
or they are both dates and have the same valueOf()
or they are both of the same type and not null and...
they are not objects and are equal per == (catches numbers/strings/booleans)
or, ignoring properties with undefined value they have the same properties all of which are considered recursively equivalent.
Functions are not considered identical by function text. This test is insufficient because functions may have differing closures. Functions are only considered equal if === says so (but you could easily extend that equivalent relation should you choose to do so).
Infinite loops, potentially caused by circular datastructures, are avoided. When areEquivalent attempts to disprove equality and recurses into an object's properties to do so, it keeps track of the objects for which this sub-comparison is needed. If equality can be disproved, then some reachable property path differs between the objects, and then there must be a shortest such reachable path, and that shortest reachable path cannot contain cycles present in both paths; i.e. it is OK to assume equality when recursively comparing objects. The assumption is stored in a property areEquivalent_Eq_91_2_34, which is deleted after use, but if the object graph already contains such a property, behavior is undefined. The use of such a marker property is necessary because javascript doesn't support dictionaries using arbitrary objects as keys.
function unwrapStringOrNumber(obj) {
return (obj instanceof Number || obj instanceof String
? obj.valueOf()
: obj);
}
function areEquivalent(a, b) {
a = unwrapStringOrNumber(a);
b = unwrapStringOrNumber(b);
if (a === b) return true; //e.g. a and b both null
if (a === null || b === null || typeof (a) !== typeof (b)) return false;
if (a instanceof Date)
return b instanceof Date && a.valueOf() === b.valueOf();
if (typeof (a) !== "object")
return a == b; //for boolean, number, string, xml
var newA = (a.areEquivalent_Eq_91_2_34 === undefined),
newB = (b.areEquivalent_Eq_91_2_34 === undefined);
try {
if (newA) a.areEquivalent_Eq_91_2_34 = [];
else if (a.areEquivalent_Eq_91_2_34.some(
function (other) { return other === b; })) return true;
if (newB) b.areEquivalent_Eq_91_2_34 = [];
else if (b.areEquivalent_Eq_91_2_34.some(
function (other) { return other === a; })) return true;
a.areEquivalent_Eq_91_2_34.push(b);
b.areEquivalent_Eq_91_2_34.push(a);
var tmp = {};
for (var prop in a)
if(prop != "areEquivalent_Eq_91_2_34")
tmp[prop] = null;
for (var prop in b)
if (prop != "areEquivalent_Eq_91_2_34")
tmp[prop] = null;
for (var prop in tmp)
if (!areEquivalent(a[prop], b[prop]))
return false;
return true;
} finally {
if (newA) delete a.areEquivalent_Eq_91_2_34;
if (newB) delete b.areEquivalent_Eq_91_2_34;
}
}
I wrote this piece of code for object comparison, and it seems to work. check the assertions:
function countProps(obj) {
var count = 0;
for (k in obj) {
if (obj.hasOwnProperty(k)) {
count++;
}
}
return count;
};
function objectEquals(v1, v2) {
if (typeof(v1) !== typeof(v2)) {
return false;
}
if (typeof(v1) === "function") {
return v1.toString() === v2.toString();
}
if (v1 instanceof Object && v2 instanceof Object) {
if (countProps(v1) !== countProps(v2)) {
return false;
}
var r = true;
for (k in v1) {
r = objectEquals(v1[k], v2[k]);
if (!r) {
return false;
}
}
return true;
} else {
return v1 === v2;
}
}
assert.isTrue(objectEquals(null,null));
assert.isFalse(objectEquals(null,undefined));
assert.isTrue(objectEquals("hi","hi"));
assert.isTrue(objectEquals(5,5));
assert.isFalse(objectEquals(5,10));
assert.isTrue(objectEquals([],[]));
assert.isTrue(objectEquals([1,2],[1,2]));
assert.isFalse(objectEquals([1,2],[2,1]));
assert.isFalse(objectEquals([1,2],[1,2,3]));
assert.isTrue(objectEquals({},{}));
assert.isTrue(objectEquals({a:1,b:2},{a:1,b:2}));
assert.isTrue(objectEquals({a:1,b:2},{b:2,a:1}));
assert.isFalse(objectEquals({a:1,b:2},{a:1,b:3}));
assert.isTrue(objectEquals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}},{1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}));
assert.isFalse(objectEquals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}},{1:{name:"mhc",age:28}, 2:{name:"arb",age:27}}));
assert.isTrue(objectEquals(function(x){return x;},function(x){return x;}));
assert.isFalse(objectEquals(function(x){return x;},function(y){return y+2;}));
I have modified a bit the code above. for me 0 !== false and null !== undefined. If you do not need such strict check remove one "=" sign in "this[p] !== x[p]" inside the code.
Object.prototype.equals = function(x){
for (var p in this) {
if(typeof(this[p]) !== typeof(x[p])) return false;
if((this[p]===null) !== (x[p]===null)) return false;
switch (typeof(this[p])) {
case 'undefined':
if (typeof(x[p]) != 'undefined') return false;
break;
case 'object':
if(this[p]!==null && x[p]!==null && (this[p].constructor.toString() !== x[p].constructor.toString() || !this[p].equals(x[p]))) return false;
break;
case 'function':
if (p != 'equals' && this[p].toString() != x[p].toString()) return false;
break;
default:
if (this[p] !== x[p]) return false;
}
}
return true;
}
Then I have tested it with next objects:
var a = {a: 'text', b:[0,1]};
var b = {a: 'text', b:[0,1]};
var c = {a: 'text', b: 0};
var d = {a: 'text', b: false};
var e = {a: 'text', b:[1,0]};
var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
var i = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var j = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var k = {a: 'text', b: null};
var l = {a: 'text', b: undefined};
a==b expected true; returned true
a==c expected false; returned false
c==d expected false; returned false
a==e expected false; returned false
f==g expected true; returned true
h==g expected false; returned false
i==j expected true; returned true
d==k expected false; returned false
k==l expected false; returned false
Here is my version, pretty much stuff from this thread is integrated (same counts for the test cases):
Object.defineProperty(Object.prototype, "equals", {
enumerable: false,
value: function (obj) {
var p;
if (this === obj) {
return true;
}
// some checks for native types first
// function and sring
if (typeof(this) === "function" || typeof(this) === "string" || this instanceof String) {
return this.toString() === obj.toString();
}
// number
if (this instanceof Number || typeof(this) === "number") {
if (obj instanceof Number || typeof(obj) === "number") {
return this.valueOf() === obj.valueOf();
}
return false;
}
// null.equals(null) and undefined.equals(undefined) do not inherit from the
// Object.prototype so we can return false when they are passed as obj
if (typeof(this) !== typeof(obj) || obj === null || typeof(obj) === "undefined") {
return false;
}
function sort (o) {
var result = {};
if (typeof o !== "object") {
return o;
}
Object.keys(o).sort().forEach(function (key) {
result[key] = sort(o[key]);
});
return result;
}
if (typeof(this) === "object") {
if (Array.isArray(this)) { // check on arrays
return JSON.stringify(this) === JSON.stringify(obj);
} else { // anyway objects
for (p in this) {
if (typeof(this[p]) !== typeof(obj[p])) {
return false;
}
if ((this[p] === null) !== (obj[p] === null)) {
return false;
}
switch (typeof(this[p])) {
case 'undefined':
if (typeof(obj[p]) !== 'undefined') {
return false;
}
break;
case 'object':
if (this[p] !== null
&& obj[p] !== null
&& (this[p].constructor.toString() !== obj[p].constructor.toString()
|| !this[p].equals(obj[p]))) {
return false;
}
break;
case 'function':
if (this[p].toString() !== obj[p].toString()) {
return false;
}
break;
default:
if (this[p] !== obj[p]) {
return false;
}
}
};
}
}
// at least check them with JSON
return JSON.stringify(sort(this)) === JSON.stringify(sort(obj));
}
});
Here is my TestCase:
assertFalse({}.equals(null));
assertFalse({}.equals(undefined));
assertTrue("String", "hi".equals("hi"));
assertTrue("Number", new Number(5).equals(5));
assertFalse("Number", new Number(5).equals(10));
assertFalse("Number+String", new Number(1).equals("1"));
assertTrue([].equals([]));
assertTrue([1,2].equals([1,2]));
assertFalse([1,2].equals([2,1]));
assertFalse([1,2].equals([1,2,3]));
assertTrue(new Date("2011-03-31").equals(new Date("2011-03-31")));
assertFalse(new Date("2011-03-31").equals(new Date("1970-01-01")));
assertTrue({}.equals({}));
assertTrue({a:1,b:2}.equals({a:1,b:2}));
assertTrue({a:1,b:2}.equals({b:2,a:1}));
assertFalse({a:1,b:2}.equals({a:1,b:3}));
assertTrue({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}));
assertFalse({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:27}}));
assertTrue("Function", (function(x){return x;}).equals(function(x){return x;}));
assertFalse("Function", (function(x){return x;}).equals(function(y){return y+2;}));
var a = {a: 'text', b:[0,1]};
var b = {a: 'text', b:[0,1]};
var c = {a: 'text', b: 0};
var d = {a: 'text', b: false};
var e = {a: 'text', b:[1,0]};
var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
var i = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var j = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var k = {a: 'text', b: null};
var l = {a: 'text', b: undefined};
assertTrue(a.equals(b));
assertFalse(a.equals(c));
assertFalse(c.equals(d));
assertFalse(a.equals(e));
assertTrue(f.equals(g));
assertFalse(h.equals(g));
assertTrue(i.equals(j));
assertFalse(d.equals(k));
assertFalse(k.equals(l));
If you work without the JSON library, maybe this will help you out:
Object.prototype.equals = function(b) {
var a = this;
for(i in a) {
if(typeof b[i] == 'undefined') {
return false;
}
if(typeof b[i] == 'object') {
if(!b[i].equals(a[i])) {
return false;
}
}
if(b[i] != a[i]) {
return false;
}
}
for(i in b) {
if(typeof a[i] == 'undefined') {
return false;
}
if(typeof a[i] == 'object') {
if(!a[i].equals(b[i])) {
return false;
}
}
if(a[i] != b[i]) {
return false;
}
}
return true;
}
var a = {foo:'bar', bar: {blub:'bla'}};
var b = {foo:'bar', bar: {blub:'blob'}};
alert(a.equals(b)); // alert's a false
if you want to check for methods explicitly you can use the method.toSource() or method.toString() methods.

What doesn't this comparison in JavaScript return true? What is going on in the backgound? [duplicate]

This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Closed 6 years ago.
What is the best way to compare objects in JavaScript?
Example:
var user1 = {name : "nerd", org: "dev"};
var user2 = {name : "nerd", org: "dev"};
var eq = user1 == user2;
alert(eq); // gives false
I know that two objects are equal if they refer to the exact same object, but is there a way to check if they have the same attributes' values?
The following way works for me, but is it the only possibility?
var eq = Object.toJSON(user1) == Object.toJSON(user2);
alert(eq); // gives true
Unfortunately there is no perfect way, unless you use _proto_ recursively and access all non-enumerable properties, but this works in Firefox only.
So the best I can do is to guess usage scenarios.
1) Fast and limited.
Works when you have simple JSON-style objects without methods and DOM nodes inside:
JSON.stringify(obj1) === JSON.stringify(obj2)
The ORDER of the properties IS IMPORTANT, so this method will return false for following objects:
x = {a: 1, b: 2};
y = {b: 2, a: 1};
2) Slow and more generic.
Compares objects without digging into prototypes, then compares properties' projections recursively, and also compares constructors.
This is almost correct algorithm:
function deepCompare () {
var i, l, leftChain, rightChain;
function compare2Objects (x, y) {
var p;
// remember that NaN === NaN returns false
// and isNaN(undefined) returns true
if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
return true;
}
// Compare primitives and functions.
// Check if both arguments link to the same object.
// Especially useful on the step where we compare prototypes
if (x === y) {
return true;
}
// Works in case when functions are created in constructor.
// Comparing dates is a common scenario. Another built-ins?
// We can even handle functions passed across iframes
if ((typeof x === 'function' && typeof y === 'function') ||
(x instanceof Date && y instanceof Date) ||
(x instanceof RegExp && y instanceof RegExp) ||
(x instanceof String && y instanceof String) ||
(x instanceof Number && y instanceof Number)) {
return x.toString() === y.toString();
}
// At last checking prototypes as good as we can
if (!(x instanceof Object && y instanceof Object)) {
return false;
}
if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
return false;
}
if (x.constructor !== y.constructor) {
return false;
}
if (x.prototype !== y.prototype) {
return false;
}
// Check for infinitive linking loops
if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
return false;
}
// Quick checking of one object being a subset of another.
// todo: cache the structure of arguments[0] for performance
for (p in y) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
}
else if (typeof y[p] !== typeof x[p]) {
return false;
}
}
for (p in x) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
}
else if (typeof y[p] !== typeof x[p]) {
return false;
}
switch (typeof (x[p])) {
case 'object':
case 'function':
leftChain.push(x);
rightChain.push(y);
if (!compare2Objects (x[p], y[p])) {
return false;
}
leftChain.pop();
rightChain.pop();
break;
default:
if (x[p] !== y[p]) {
return false;
}
break;
}
}
return true;
}
if (arguments.length < 1) {
return true; //Die silently? Don't know how to handle such case, please help...
// throw "Need two or more arguments to compare";
}
for (i = 1, l = arguments.length; i < l; i++) {
leftChain = []; //Todo: this can be cached
rightChain = [];
if (!compare2Objects(arguments[0], arguments[i])) {
return false;
}
}
return true;
}
Known issues (well, they have very low priority, probably you'll never notice them):
objects with different prototype structure but same projection
functions may have identical text but refer to different closures
Tests: passes tests are from How to determine equality for two JavaScript objects?.
Here is my ES3 commented solution (gory details after the code):
function object_equals( x, y ) {
if ( x === y ) return true;
// if both x and y are null or undefined and exactly the same
if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
// if they are not strictly equal, they both need to be Objects
if ( x.constructor !== y.constructor ) return false;
// they must have the exact same prototype chain, the closest we can do is
// test there constructor.
for ( var p in x ) {
if ( ! x.hasOwnProperty( p ) ) continue;
// other properties were tested using x.constructor === y.constructor
if ( ! y.hasOwnProperty( p ) ) return false;
// allows to compare x[ p ] and y[ p ] when set to undefined
if ( x[ p ] === y[ p ] ) continue;
// if they have the same strict value or identity then they are equal
if ( typeof( x[ p ] ) !== "object" ) return false;
// Numbers, Strings, Functions, Booleans must be strictly equal
if ( ! object_equals( x[ p ], y[ p ] ) ) return false;
// Objects and Arrays must be tested recursively
}
for ( p in y )
if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) )
return false;
// allows x[ p ] to be set to undefined
return true;
}
In developing this solution, I took a particular look at corner cases, efficiency, yet trying to yield a simple solution that works, hopefully with some elegance. JavaScript allows both null and undefined properties and objects have prototypes chains that can lead to very different behaviors if not checked.
First I have chosen to not extend Object.prototype, mostly because null could not be one of the objects of the comparison and that I believe that null should be a valid object to compare with another. There are also other legitimate concerns noted by others regarding the extension of Object.prototype regarding possible side effects on other's code.
Special care must taken to deal the possibility that JavaScript allows object properties can be set to undefined, i.e. there exists properties which values are set to undefined. The above solution verifies that both objects have the same properties set to undefined to report equality. This can only be accomplished by checking the existence of properties using Object.hasOwnProperty( property_name ). Also note that JSON.stringify() removes properties that are set to undefined, and that therefore comparisons using this form will ignore properties set to the value undefined.
Functions should be considered equal only if they share the same reference, not just the same code, because this would not take into account these functions prototype. So comparing the code string does not work to guaranty that they have the same prototype object.
The two objects should have the same prototype chain, not just the same properties. This can only be tested cross-browser by comparing the constructor of both objects for strict equality. ECMAScript 5 would allow to test their actual prototype using Object.getPrototypeOf(). Some web browsers also offer a __proto__ property that does the same thing. A possible improvement of the above code would allow to use one of these methods whenever available.
The use of strict comparisons is paramount here because 2 should not be considered equal to "2.0000", nor false should be considered equal to null, undefined, or 0.
Efficiency considerations lead me to compare for equality of properties as soon as possible. Then, only if that failed, look for the typeof these properties. The speed boost could be significant on large objects with lots of scalar properties.
No more that two loops are required, the first to check properties from the left object, the second to check properties from the right and verify only existence (not value), to catch these properties which are defined with the undefined value.
Overall this code handles most corner cases in only 16 lines of code (without comments).
Update (8/13/2015). I have implemented a better version, as the function value_equals() that is faster, handles properly corner cases such as NaN and 0 different than -0, optionally enforcing objects' properties order and testing for cyclic references, backed by more than 100 automated tests as part of the Toubkal project test suite.
Utils.compareObjects = function(o1, o2){
for(var p in o1){
if(o1.hasOwnProperty(p)){
if(o1[p] !== o2[p]){
return false;
}
}
}
for(var p in o2){
if(o2.hasOwnProperty(p)){
if(o1[p] !== o2[p]){
return false;
}
}
}
return true;
};
Simple way to compare ONE-LEVEL only objects.
Certainly not the only way - you could prototype a method (against Object here but I certainly wouldn't suggest using Object for live code) to replicate C#/Java style comparison methods.
Edit, since a general example seems to be expected:
Object.prototype.equals = function(x)
{
for(p in this)
{
switch(typeof(this[p]))
{
case 'object':
if (!this[p].equals(x[p])) { return false }; break;
case 'function':
if (typeof(x[p])=='undefined' || (p != 'equals' && this[p].toString() != x[p].toString())) { return false; }; break;
default:
if (this[p] != x[p]) { return false; }
}
}
for(p in x)
{
if(typeof(this[p])=='undefined') {return false;}
}
return true;
}
Note that testing methods with toString() is absolutely not good enough but a method which would be acceptable is very hard because of the problem of whitespace having meaning or not, never mind synonym methods and methods producing the same result with different implementations. And the problems of prototyping against Object in general.
The following algorithm will deal with self-referential data structures, numbers, strings, dates, and of course plain nested javascript objects:
Objects are considered equivalent when
They are exactly equal per === (String and Number are unwrapped first to ensure 42 is equivalent to Number(42))
or they are both dates and have the same valueOf()
or they are both of the same type and not null and...
they are not objects and are equal per == (catches numbers/strings/booleans)
or, ignoring properties with undefined value they have the same properties all of which are considered recursively equivalent.
Functions are not considered identical by function text. This test is insufficient because functions may have differing closures. Functions are only considered equal if === says so (but you could easily extend that equivalent relation should you choose to do so).
Infinite loops, potentially caused by circular datastructures, are avoided. When areEquivalent attempts to disprove equality and recurses into an object's properties to do so, it keeps track of the objects for which this sub-comparison is needed. If equality can be disproved, then some reachable property path differs between the objects, and then there must be a shortest such reachable path, and that shortest reachable path cannot contain cycles present in both paths; i.e. it is OK to assume equality when recursively comparing objects. The assumption is stored in a property areEquivalent_Eq_91_2_34, which is deleted after use, but if the object graph already contains such a property, behavior is undefined. The use of such a marker property is necessary because javascript doesn't support dictionaries using arbitrary objects as keys.
function unwrapStringOrNumber(obj) {
return (obj instanceof Number || obj instanceof String
? obj.valueOf()
: obj);
}
function areEquivalent(a, b) {
a = unwrapStringOrNumber(a);
b = unwrapStringOrNumber(b);
if (a === b) return true; //e.g. a and b both null
if (a === null || b === null || typeof (a) !== typeof (b)) return false;
if (a instanceof Date)
return b instanceof Date && a.valueOf() === b.valueOf();
if (typeof (a) !== "object")
return a == b; //for boolean, number, string, xml
var newA = (a.areEquivalent_Eq_91_2_34 === undefined),
newB = (b.areEquivalent_Eq_91_2_34 === undefined);
try {
if (newA) a.areEquivalent_Eq_91_2_34 = [];
else if (a.areEquivalent_Eq_91_2_34.some(
function (other) { return other === b; })) return true;
if (newB) b.areEquivalent_Eq_91_2_34 = [];
else if (b.areEquivalent_Eq_91_2_34.some(
function (other) { return other === a; })) return true;
a.areEquivalent_Eq_91_2_34.push(b);
b.areEquivalent_Eq_91_2_34.push(a);
var tmp = {};
for (var prop in a)
if(prop != "areEquivalent_Eq_91_2_34")
tmp[prop] = null;
for (var prop in b)
if (prop != "areEquivalent_Eq_91_2_34")
tmp[prop] = null;
for (var prop in tmp)
if (!areEquivalent(a[prop], b[prop]))
return false;
return true;
} finally {
if (newA) delete a.areEquivalent_Eq_91_2_34;
if (newB) delete b.areEquivalent_Eq_91_2_34;
}
}
I wrote this piece of code for object comparison, and it seems to work. check the assertions:
function countProps(obj) {
var count = 0;
for (k in obj) {
if (obj.hasOwnProperty(k)) {
count++;
}
}
return count;
};
function objectEquals(v1, v2) {
if (typeof(v1) !== typeof(v2)) {
return false;
}
if (typeof(v1) === "function") {
return v1.toString() === v2.toString();
}
if (v1 instanceof Object && v2 instanceof Object) {
if (countProps(v1) !== countProps(v2)) {
return false;
}
var r = true;
for (k in v1) {
r = objectEquals(v1[k], v2[k]);
if (!r) {
return false;
}
}
return true;
} else {
return v1 === v2;
}
}
assert.isTrue(objectEquals(null,null));
assert.isFalse(objectEquals(null,undefined));
assert.isTrue(objectEquals("hi","hi"));
assert.isTrue(objectEquals(5,5));
assert.isFalse(objectEquals(5,10));
assert.isTrue(objectEquals([],[]));
assert.isTrue(objectEquals([1,2],[1,2]));
assert.isFalse(objectEquals([1,2],[2,1]));
assert.isFalse(objectEquals([1,2],[1,2,3]));
assert.isTrue(objectEquals({},{}));
assert.isTrue(objectEquals({a:1,b:2},{a:1,b:2}));
assert.isTrue(objectEquals({a:1,b:2},{b:2,a:1}));
assert.isFalse(objectEquals({a:1,b:2},{a:1,b:3}));
assert.isTrue(objectEquals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}},{1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}));
assert.isFalse(objectEquals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}},{1:{name:"mhc",age:28}, 2:{name:"arb",age:27}}));
assert.isTrue(objectEquals(function(x){return x;},function(x){return x;}));
assert.isFalse(objectEquals(function(x){return x;},function(y){return y+2;}));
I have modified a bit the code above. for me 0 !== false and null !== undefined. If you do not need such strict check remove one "=" sign in "this[p] !== x[p]" inside the code.
Object.prototype.equals = function(x){
for (var p in this) {
if(typeof(this[p]) !== typeof(x[p])) return false;
if((this[p]===null) !== (x[p]===null)) return false;
switch (typeof(this[p])) {
case 'undefined':
if (typeof(x[p]) != 'undefined') return false;
break;
case 'object':
if(this[p]!==null && x[p]!==null && (this[p].constructor.toString() !== x[p].constructor.toString() || !this[p].equals(x[p]))) return false;
break;
case 'function':
if (p != 'equals' && this[p].toString() != x[p].toString()) return false;
break;
default:
if (this[p] !== x[p]) return false;
}
}
return true;
}
Then I have tested it with next objects:
var a = {a: 'text', b:[0,1]};
var b = {a: 'text', b:[0,1]};
var c = {a: 'text', b: 0};
var d = {a: 'text', b: false};
var e = {a: 'text', b:[1,0]};
var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
var i = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var j = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var k = {a: 'text', b: null};
var l = {a: 'text', b: undefined};
a==b expected true; returned true
a==c expected false; returned false
c==d expected false; returned false
a==e expected false; returned false
f==g expected true; returned true
h==g expected false; returned false
i==j expected true; returned true
d==k expected false; returned false
k==l expected false; returned false
Here is my version, pretty much stuff from this thread is integrated (same counts for the test cases):
Object.defineProperty(Object.prototype, "equals", {
enumerable: false,
value: function (obj) {
var p;
if (this === obj) {
return true;
}
// some checks for native types first
// function and sring
if (typeof(this) === "function" || typeof(this) === "string" || this instanceof String) {
return this.toString() === obj.toString();
}
// number
if (this instanceof Number || typeof(this) === "number") {
if (obj instanceof Number || typeof(obj) === "number") {
return this.valueOf() === obj.valueOf();
}
return false;
}
// null.equals(null) and undefined.equals(undefined) do not inherit from the
// Object.prototype so we can return false when they are passed as obj
if (typeof(this) !== typeof(obj) || obj === null || typeof(obj) === "undefined") {
return false;
}
function sort (o) {
var result = {};
if (typeof o !== "object") {
return o;
}
Object.keys(o).sort().forEach(function (key) {
result[key] = sort(o[key]);
});
return result;
}
if (typeof(this) === "object") {
if (Array.isArray(this)) { // check on arrays
return JSON.stringify(this) === JSON.stringify(obj);
} else { // anyway objects
for (p in this) {
if (typeof(this[p]) !== typeof(obj[p])) {
return false;
}
if ((this[p] === null) !== (obj[p] === null)) {
return false;
}
switch (typeof(this[p])) {
case 'undefined':
if (typeof(obj[p]) !== 'undefined') {
return false;
}
break;
case 'object':
if (this[p] !== null
&& obj[p] !== null
&& (this[p].constructor.toString() !== obj[p].constructor.toString()
|| !this[p].equals(obj[p]))) {
return false;
}
break;
case 'function':
if (this[p].toString() !== obj[p].toString()) {
return false;
}
break;
default:
if (this[p] !== obj[p]) {
return false;
}
}
};
}
}
// at least check them with JSON
return JSON.stringify(sort(this)) === JSON.stringify(sort(obj));
}
});
Here is my TestCase:
assertFalse({}.equals(null));
assertFalse({}.equals(undefined));
assertTrue("String", "hi".equals("hi"));
assertTrue("Number", new Number(5).equals(5));
assertFalse("Number", new Number(5).equals(10));
assertFalse("Number+String", new Number(1).equals("1"));
assertTrue([].equals([]));
assertTrue([1,2].equals([1,2]));
assertFalse([1,2].equals([2,1]));
assertFalse([1,2].equals([1,2,3]));
assertTrue(new Date("2011-03-31").equals(new Date("2011-03-31")));
assertFalse(new Date("2011-03-31").equals(new Date("1970-01-01")));
assertTrue({}.equals({}));
assertTrue({a:1,b:2}.equals({a:1,b:2}));
assertTrue({a:1,b:2}.equals({b:2,a:1}));
assertFalse({a:1,b:2}.equals({a:1,b:3}));
assertTrue({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}));
assertFalse({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:27}}));
assertTrue("Function", (function(x){return x;}).equals(function(x){return x;}));
assertFalse("Function", (function(x){return x;}).equals(function(y){return y+2;}));
var a = {a: 'text', b:[0,1]};
var b = {a: 'text', b:[0,1]};
var c = {a: 'text', b: 0};
var d = {a: 'text', b: false};
var e = {a: 'text', b:[1,0]};
var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
var i = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var j = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var k = {a: 'text', b: null};
var l = {a: 'text', b: undefined};
assertTrue(a.equals(b));
assertFalse(a.equals(c));
assertFalse(c.equals(d));
assertFalse(a.equals(e));
assertTrue(f.equals(g));
assertFalse(h.equals(g));
assertTrue(i.equals(j));
assertFalse(d.equals(k));
assertFalse(k.equals(l));
If you work without the JSON library, maybe this will help you out:
Object.prototype.equals = function(b) {
var a = this;
for(i in a) {
if(typeof b[i] == 'undefined') {
return false;
}
if(typeof b[i] == 'object') {
if(!b[i].equals(a[i])) {
return false;
}
}
if(b[i] != a[i]) {
return false;
}
}
for(i in b) {
if(typeof a[i] == 'undefined') {
return false;
}
if(typeof a[i] == 'object') {
if(!a[i].equals(b[i])) {
return false;
}
}
if(a[i] != b[i]) {
return false;
}
}
return true;
}
var a = {foo:'bar', bar: {blub:'bla'}};
var b = {foo:'bar', bar: {blub:'blob'}};
alert(a.equals(b)); // alert's a false
if you want to check for methods explicitly you can use the method.toSource() or method.toString() methods.

Compare arrays as (multi-) sets

I'm looking for an efficient way to find out whether two arrays contain same amounts of equal elements (in the == sense), in any order:
foo = {/*some object*/}
bar = {/*some other object*/}
a = [1,2,foo,2,bar,2]
b = [bar,2,2,2,foo,1]
sameElements(a, b) --> true
PS. Note that pretty much every solution in the thread uses === and not == for comparison. This is fine for my needs though.
Update 5
I posted a new answer with a different approach.
Update
I extended the code to have the possibility of either checking by reference or equality
just pass true as second parameter to do a reference check.
Also I added the example to Brunos JSPerf
It runs at about 11 ops/s doing a reference check
I will comment the code as soon(!) as I get some spare time to explain it a bit more, but at the moment don't have the time for that, sry. Done
Update 2.
Like Bruno pointed out in the comments sameElements([NaN],[NaN]) yields false
In my opinion this is the correct behaviour as NaN is ambigious and should always lead to a false result,at least when comparing NaN.equals(NaN). But he had quite a good point.
Whether
[1,2,foo,bar,NaN,3] should be equal to [1,3,foo,NaN,bar,2] or not.
Ok.. honestly I'm a bit torn whether it should or not, so i added two flags.
Number.prototype.equal.NaN
If true
NaN.equals(NaN) //true
Array.prototype.equal.NaN
If true
[NaN].equals([NaN],true) //true
note this is only for reference checks. As a deep check would invoke Number.prototype.equals anyway
Update 3:
Dang i totally missed 2 lines in the sort function.
Added
r[0] = a._srt; //DANG i totally missed this line
r[1] = b._srt; //And this.
Line 105 in the Fiddle
Which is kind of important as it determines the consistent order of the Elements.
Update 4
I tried to optimize the sort function a bit, and managed to get it up to about 20 ops/s.
Below is the updated code, as well as the updated fiddle =)
Also i chose to mark the objects outside the sort function, it doesn't seem to make a performance difference anymore, and its more readable
Here is an approach using Object.defineProperty to add equals functions to
Array,Object,Number,String,Boolean's prototype to avoid typechecking in one function for
performance reasons. As we can recursively call .equals on any element.
But of course checking Objects for equality may cause performance issues in big Objects.
So if anyone feels unpleasant manipulating native prototypes, just do a type check and put it into one function
Object.defineProperty(Boolean.prototype, "equals", {
enumerable: false,
configurable: true,
value: function (c) {
return this == c; //For booleans simply return the equality
}
});
Object.defineProperty(Number.prototype, "equals", {
enumerable: false,
configurable: true,
value: function (c) {
if (Number.prototype.equals.NaN == true && isNaN(this) && c != c) return true; //let NaN equals NaN if flag set
return this == c; // else do a normal compare
}
});
Number.prototype.equals.NaN = false; //Set to true to return true for NaN == NaN
Object.defineProperty(String.prototype, "equals", {
enumerable: false,
configurable: true,
value: Boolean.prototype.equals //the same (now we covered the primitives)
});
Object.defineProperty(Object.prototype, "equals", {
enumerable: false,
configurable: true,
value: function (c, reference) {
if (true === reference) //If its a check by reference
return this === c; //return the result of comparing the reference
if (typeof this != typeof c) {
return false; //if the types don't match (Object equals primitive) immediately return
}
var d = [Object.keys(this), Object.keys(c)],//create an array with the keys of the objects, which get compared
f = d[0].length; //store length of keys of the first obj (we need it later)
if (f !== d[1].length) {//If the Objects differ in the length of their keys
return false; //immediately return
}
for (var e = 0; e < f; e++) { //iterate over the keys of the first object
if (d[0][e] != d[1][e] || !this[d[0][e]].equals(c[d[1][e]])) {
return false; //if either the key name does not match or the value does not match, return false. a call of .equal on 2 primitives simply compares them as e.g Number.prototype.equal gets called
}
}
return true; //everything is equal, return true
}
});
Object.defineProperty(Array.prototype, "equals", {
enumerable: false,
configurable: true,
value: function (c,reference) {
var d = this.length;
if (d != c.length) {
return false;
}
var f = Array.prototype.equals.sort(this.concat());
c = Array.prototype.equals.sort(c.concat(),f)
if (reference){
for (var e = 0; e < d; e++) {
if (f[e] != c[e] && !(Array.prototype.equals.NaN && f[e] != f[e] && c[e] != c[e])) {
return false;
}
}
} else {
for (var e = 0; e < d; e++) {
if (!f[e].equals(c[e])) {
return false;
}
}
}
return true;
}
});
Array.prototype.equals.NaN = false; //Set to true to allow [NaN].equals([NaN]) //true
Object.defineProperty(Array.prototype.equals,"sort",{
enumerable:false,
value:function sort (curr,prev) {
var weight = {
"[object Undefined]":6,
"[object Object]":5,
"[object Null]":4,
"[object String]":3,
"[object Number]":2,
"[object Boolean]":1
}
if (prev) { //mark the objects
for (var i = prev.length,j,t;i>0;i--) {
t = typeof (j = prev[i]);
if (j != null && t === "object") {
j._pos = i;
} else if (t !== "object" && t != "undefined" ) break;
}
}
curr.sort (sorter);
if (prev) {
for (var k = prev.length,l,t;k>0;k--) {
t = typeof (l = prev[k]);
if (t === "object" && l != null) {
delete l._pos;
} else if (t !== "object" && t != "undefined" ) break;
}
}
return curr;
function sorter (a,b) {
var tStr = Object.prototype.toString
var types = [tStr.call(a),tStr.call(b)]
var ret = [0,0];
if (types[0] === types[1] && types[0] === "[object Object]") {
if (prev) return a._pos - b._pos
else {
return a === b ? 0 : 1;
}
} else if (types [0] !== types [1]){
return weight[types[0]] - weight[types[1]]
}
return a>b?1:a<b?-1:0;
}
}
});
With this we can reduce the sameElements function to
function sameElements(c, d,referenceCheck) {
return c.equals(d,referenceCheck); //call .equals of Array.prototype.
}
Note. of course you could put all equal functions into the sameElements function, for the cost of the typechecking.
Now here are 3 examples: 1 with deep checking, 2 with reference checking.
var foo = {
a: 1,
obj: {
number: 2,
bool: true,
string: "asd"
},
arr: [1, 2, 3]
};
var bar = {
a: 1,
obj: {
number: 2,
bool: true,
string: "asd"
},
arr: [1, 2, 3]
};
var foobar = {
a: 1,
obj: {
number: 2,
bool: true,
string: "asd"
},
arr: [1, 2, 3, 4]
};
var a = [1, 2, foo, 2, bar, 2];
var b = [foo, 2, 2, 2, bar, 1];
var c = [bar, 2, 2, 2, bar, 1];
So these are the Arrays we compare. And the output is
Check a and b with references only.
console.log (sameElements ( a,b,true)) //true As they contain the same elements
Check b and c with references only
console.log (sameElements (b,c,true)) //false as c contains bar twice.
Check b and c deeply
console.log (sameElements (b,c,false)) //true as bar and foo are equal but not the same
Check for 2 Arrays containing NaN
Array.prototype.equals.NaN = true;
console.log(sameElements([NaN],[NaN],true)); //true.
Array.prototype.equals.NaN = false;
Demo on JSFiddle
You can implement the following algorithm:
If a and b do not have the same length:
Return false.
Otherwise:
Clone b,
For each item in a:
If the item exists in our clone of b:
Remove the item from our clone of b,
Otherwise:
Return false.
Return true.
With Javascript 1.6, you can use every() and indexOf() to write:
function sameElements(a, b)
{
if (a.length != b.length) {
return false;
}
var ourB = b.concat();
return a.every(function(item) {
var index = ourB.indexOf(item);
if (index < 0) {
return false;
} else {
ourB.splice(index, 1);
return true;
}
});
}
Note this implementation does not completely fulfill your requirements because indexOf() uses strict equality (===) internally. If you really want non-strict equality (==), you will have to write an inner loop instead.
Like this perhaps?
var foo = {}; var bar=[];
var a = [3,2,1,foo]; var b = [foo,1,2,3];
function comp(a,b)
{
// immediately discard if they are of different sizes
if (a.length != b.length) return false;
b = b.slice(0); // clone to keep original values after the function
a.forEach(function(e) {
var i;
if ((i = b.indexOf(e)) != -1)
b.splice(i, 1);
});
return !b.length;
}
comp(a,b);
UPDATE
As #Bergi and #thg435 point out my previous implementation was flawed so here is another implementation:
function sameElements(a, b) {
var objs = [];
// if length is not the same then must not be equal
if (a.length != b.length) return false;
// do an initial sort which will group types
a.sort();
b.sort();
for ( var i = 0; i < a.length; i++ ) {
var aIsPrimitive = isPrimitive(a[i]);
var bIsPrimitive = isPrimitive(b[i]);
// NaN will not equal itself
if( a[i] !== a[i] ) {
if( b[i] === b[i] ) {
return false;
}
}
else if (aIsPrimitive && bIsPrimitive) {
if( a[i] != b[i] ) return false;
}
// if not primitive increment the __count property
else if (!aIsPrimitive && !bIsPrimitive) {
incrementCountA(a[i]);
incrementCountB(b[i]);
// keep track on non-primitive objects
objs.push(i);
}
// if both types are not the same then this array
// contains different number of primitives
else {
return false;
}
}
var result = true;
for (var i = 0; i < objs.length; i++) {
var ind = objs[i];
// if __aCount and __bCount match then object exists same
// number of times in both arrays
if( a[ind].__aCount !== a[ind].__bCount ) result = false;
if( b[ind].__aCount !== b[ind].__bCount ) result = false;
// revert object to what it was
// before entering this function
delete a[ind].__aCount;
delete a[ind].__bCount;
delete b[ind].__aCount;
delete b[ind].__bCount;
}
return result;
}
// inspired by #Bergi's code
function isPrimitive(arg) {
return Object(arg) !== arg;
}
function incrementCountA(arg) {
if (arg.hasOwnProperty("__aCount")) {
arg.__aCount = arg.__aCount + 1;
} else {
Object.defineProperty(arg, "__aCount", {
enumerable: false,
value: 1,
writable: true,
configurable: true
});
}
}
function incrementCountB(arg) {
if (arg.hasOwnProperty("__bCount")) {
arg.__bCount = arg.__bCount + 1;
} else {
Object.defineProperty(arg, "__bCount", {
enumerable: false,
value: 1,
writable: true,
configurable: true
});
}
}
Then just call the function
sameElements( ["NaN"], [NaN] ); // false
// As "1" == 1 returns true
sameElements( [1],["1"] ); // true
sameElements( [1,2], [1,2,3] ); //false
The above implement actually defines a new property called "__count" that is used to keep track of non-primitive elements in both arrays. These are deleted before the function returns so as to leave the array elements as before.
Fiddle here
jsperf here.
The reason I changed the jsperf test case was that as #Bergi states the test arrays, especially the fact there were only 2 unique objects in the whole array is not representative of what we are testing for.
One other advantage of this implementation is that if you need to make it compatible with pre IE9 browsers instead of using the defineProperty to create a non-enumerable property you could just use a normal property.
Thanks everyone for sharing ideas! I've came up with the following
function sameElements(a, b) {
var hash = function(x) {
return typeof x + (typeof x == "object" ? a.indexOf(x) : x);
}
return a.map(hash).sort().join() == b.map(hash).sort().join();
}
This isn't the fastest solution, but IMO, most readable one so far.
i wasn't sure if "===" is ok, the question is a bit vauge...
if so, this is quite a bit faster and simpler than some other possible ways of doing it:
function isSame(a,b){
return a.length==b.length &&
a.filter(function(a){ return b.indexOf(a)!==-1 }).length == b.length;
}
Edit 2
1) Thanks to user2357112 for pointing out the Object.prototype.toString.call issue
this also showed, the reason it was that fast, that it didn't consider Arrays ...
I fixed the code,it should be working now :), unfortunately its now at about 59ops/s on chrome and 45ops/s on ff.
Fiddle and JSPerf is updated.
Edit
1)
I fixed the code, it supports mutliple variables referencing the same Object now.
A little bit slower than before, but still over 100ops/s on chrome.
2)
I tried using a bitmask instead of an array to keep multiple positions of the objects, but its nearly 15ops/s slow
3) As pointed ot in the comments i forgot to reset tmp after [[get]] is called fixed the code, the fiddle, and the perf.
So thanks to user2357112 with his Answer heres another approach using counting
var sameElements = (function () {
var f, of, objectFlagName;
of = objectFlagName = "__pos";
var tstr = function (o) {
var t = typeof o;
if (o === null)
t = "null";
return t
};
var types = {};
(function () {
var tmp = {};
Object.defineProperty(types, tstr(1), {
set: function (v) {
if (f)
tmp[v] = -~tmp[v];
else
tmp[v] = ~-tmp[v];
},
get: function () {
var ret = 1;
for (var k in tmp) {
ret &= !tmp[k];
}
tmp = {};
return ret;
}
});
})();
(function () {
var tmp = {};
Object.defineProperty(types, tstr(""), {
set: function (v) {
if (f) {
tmp[v] = -~tmp[v];
} else {
tmp[v] = ~-tmp[v];
}
},
get: function () {
var ret = 1;
for (var k in tmp) {
ret &= !tmp[k];
}
tmp = {};
return ret;
}
});
})();
(function () {
var tmp = [];
function add (v) {
tmp.push(v);
if (v[of]===undefined) {
v[of] = [tmp.length -1];
} else {
v[of].push(tmp.length -1)
}
}
Object.defineProperty(types, tstr({}), {
get: function () {
var ret = true;
for (var i = tmp.length - 1; i >= 0; i--) {
var c = tmp[i]
if (typeof c !== "undefined") {
ret = false
delete c[of]
}
}
tmp = [];
return ret;
},
set: function (v) {
var pos;
if (f) {
add (v);
} else if (!f && (pos = v[of]) !== void 0) {
tmp[pos.pop()] = undefined;
if (pos.length === 0)
delete v[of];
} else {
add (v);
}
}
});
}());
(function () {
var tmp = 0;
Object.defineProperty(types, tstr(undefined), {
get: function () {
var ret = !tmp;
tmp = 0;
return ret;
},
set: function () {
tmp += f ? 1 : -1;
}
});
})();
(function () {
var tmp = 0;
Object.defineProperty(types, tstr(null), {
get: function () {
var ret = !tmp;
tmp = 0;
return ret;
},
set: function () {
tmp += f ? 1 : -1;
}
});
})();
var tIt = [tstr(1), tstr(""), tstr({}), tstr(undefined), tstr(null)];
return function eq(a, b) {
f = true;
for (var i = a.length - 1; i >= 0; i--) {
var v = a[i];
types[tstr(v)] = v;
}
f = false;
for (var k = b.length - 1; k >= 0; k--) {
var w = b[k];
types[tstr(w)] = w;
}
var r = 1;
for (var l = 0, j; j = tIt[l]; l++) {
r &= types [j]
}
return !!r;
}
})()
Here is a JSFiddle and a JSPerf (it uses the same Arrays a and b as in the previous answers perf) with this code vs the Closure compiled
Heres the output. note: it doesn't support a deep comparison anymore, as is
var foo = {a:2}
var bar = {a:1};
var a = [1, 2, foo, 2, bar, 2];
var b = [foo, 2, 2, 2, bar, 1];
var c = [bar, 2, 2, 2, bar, 1];
console.log(sameElements([NaN],[NaN])); //true
console.log (sameElements ( a,b)) //true
console.log (sameElements (b,c)) //false
Using efficient lookup tables for the counts of the elements:
function sameElements(a) { // can compare any number of arrays
var map, maps = [], // counting booleans, numbers and strings
nulls = [], // counting undefined and null
nans = [], // counting nans
objs, counts, objects = [],
al = arguments.length;
// quick escapes:
if (al < 2)
return true;
var l0 = a.length;
if ([].slice.call(arguments).some(function(s) { return s.length != l0; }))
return false;
for (var i=0; i<al; i++) {
var multiset = arguments[i];
maps.push(map = {}); // better: Object.create(null);
objects.push({vals: objs=[], count: counts=[]});
nulls[i] = 0;
nans[i] = 0;
for (var j=0; j<l0; j++) {
var val = multiset[j];
if (val !== val)
nans[i]++;
else if (val === null)
nulls[i]++;
else if (Object(val) === val) { // non-primitive
var ind = objs.indexOf(val);
if (ind > -1)
counts[ind]++;
else
objs.push(val), counts.push(1);
} else { // booleans, strings and numbers do compare together
if (typeof val == "boolean")
val = +val;
if (val in map)
map[val]++;
else
map[val] = 1;
}
}
}
// testing if nulls and nans are the same everywhere
for (var i=1; i<al; i++)
if (nulls[i] != nulls[0] || nans[i] != nans[0])
return false;
// testing if primitives were the same everywhere
var map0 = maps[0];
for (var el in map0)
for (var i=1; i<al; i++) {
if (map0[el] !== maps[i][el])
return false;
delete maps[i][el];
}
for (var i=1; i<al; i++)
for (var el in maps[i])
return false;
// testing if objects were the same everywhere
var objs0 = objects[0].vals,
ol = objs0.length;
counts0 = objects[0].count;
for (var i=1; i<al; i++)
if (objects[i].count.length != ol)
return false;
for (var i=0; i<ol; i++)
for (var j=1; j<al; j++)
if (objects[j].count[ objects[j].vals.indexOf(objs0[i]) ] != counts0[i])
return false;
// else, the multisets are equal:
return true;
}
It still uses indexOf search amongst all objects, so if you have multisets with many different objects you might want to optimize that part as well. Have a look at Unique ID or object signature (and it's duplicate questions) for how to get lookup table keys for them. And if you don't have many primitive values in the multisets, you might just store them in arrays and sort those before comparing each item-by-item (like #Bruno did).
Disclaimer: This solution doesn't try to get the [[PrimitiveValue]] of objects, they will never be counted as equal to primitives (while == would do).
Here is the update on #Bruno's jsperf test of the answers, yet I guess only two objects (each of them present 500 times in the 10k array) and no duplicate primitive values are not representative.

Crockford's .supplant with multiple level objects

/** Supplant **/
String.prototype.supplant = function(o) {
return this.replace (/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
Crockford is no doubt a JavaScript Grand Wizard, but his prototype is lacking when it comes to multiple level objects.
I would like this function to cover multiple level object replacement such as '{post.detailed}' could anyone help me with a revised version of supplant?
That shouldn't be too difficult. Use this replace function instead:
function (a, b) {
var r = o,
parts = b.split(".");
for (var i=0; r && i<parts.length; i++)
r = r[parts[i]];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
I personally hate it when people stuff their own rubbish on the native types in JavaScript. If I were to write it I would do the following... But why no love for boolean?
function supplant(str, data) {
return str.replace(/{([^{}]*)}/g, function (a, b) {
// Split the variable into its dot notation parts
var p = b.split(/\./);
// The c variable becomes our cursor that will traverse the object
var c = data;
// Loop over the steps in the dot notation path
for(var i = 0; i < p.length; ++i) {
// If the key doesn't exist in the object do not process
// mirrors how the function worked for bad values
if(c[p[i]] == null)
return a;
// Move the cursor up to the next step
c = c[p[i]];
}
// If the data is a string or number return it otherwise do
// not process, return the value it was, i.e. {x}
return typeof c === 'string' || typeof c === 'number' ? c : a;
});
};
It doesn't support arrays btw, you would need to do some additional stuff to support that.
#Bergi method w/ support to boolean:
function (a, b) {
var r = o,
parts = b.split(".");
for (var i=0; r && i<parts.length; i++)
r = r[parts[i]];
return typeof r === 'string' || typeof r === 'number' || typeof r === 'boolean' ? r : a;
}
Original Crockford's Supplant method w/ support to boolean:
if (!String.prototype.supplant) {
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' || typeof r === 'boolean' ? r : a;
}
);
};
}
Best of luck!
https://gist.github.com/fsschmitt/b48db17397499282ff8c36d73a36a8af

Object comparison in JavaScript [duplicate]

This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Closed 6 years ago.
What is the best way to compare objects in JavaScript?
Example:
var user1 = {name : "nerd", org: "dev"};
var user2 = {name : "nerd", org: "dev"};
var eq = user1 == user2;
alert(eq); // gives false
I know that two objects are equal if they refer to the exact same object, but is there a way to check if they have the same attributes' values?
The following way works for me, but is it the only possibility?
var eq = Object.toJSON(user1) == Object.toJSON(user2);
alert(eq); // gives true
Unfortunately there is no perfect way, unless you use _proto_ recursively and access all non-enumerable properties, but this works in Firefox only.
So the best I can do is to guess usage scenarios.
1) Fast and limited.
Works when you have simple JSON-style objects without methods and DOM nodes inside:
JSON.stringify(obj1) === JSON.stringify(obj2)
The ORDER of the properties IS IMPORTANT, so this method will return false for following objects:
x = {a: 1, b: 2};
y = {b: 2, a: 1};
2) Slow and more generic.
Compares objects without digging into prototypes, then compares properties' projections recursively, and also compares constructors.
This is almost correct algorithm:
function deepCompare () {
var i, l, leftChain, rightChain;
function compare2Objects (x, y) {
var p;
// remember that NaN === NaN returns false
// and isNaN(undefined) returns true
if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
return true;
}
// Compare primitives and functions.
// Check if both arguments link to the same object.
// Especially useful on the step where we compare prototypes
if (x === y) {
return true;
}
// Works in case when functions are created in constructor.
// Comparing dates is a common scenario. Another built-ins?
// We can even handle functions passed across iframes
if ((typeof x === 'function' && typeof y === 'function') ||
(x instanceof Date && y instanceof Date) ||
(x instanceof RegExp && y instanceof RegExp) ||
(x instanceof String && y instanceof String) ||
(x instanceof Number && y instanceof Number)) {
return x.toString() === y.toString();
}
// At last checking prototypes as good as we can
if (!(x instanceof Object && y instanceof Object)) {
return false;
}
if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
return false;
}
if (x.constructor !== y.constructor) {
return false;
}
if (x.prototype !== y.prototype) {
return false;
}
// Check for infinitive linking loops
if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
return false;
}
// Quick checking of one object being a subset of another.
// todo: cache the structure of arguments[0] for performance
for (p in y) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
}
else if (typeof y[p] !== typeof x[p]) {
return false;
}
}
for (p in x) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
}
else if (typeof y[p] !== typeof x[p]) {
return false;
}
switch (typeof (x[p])) {
case 'object':
case 'function':
leftChain.push(x);
rightChain.push(y);
if (!compare2Objects (x[p], y[p])) {
return false;
}
leftChain.pop();
rightChain.pop();
break;
default:
if (x[p] !== y[p]) {
return false;
}
break;
}
}
return true;
}
if (arguments.length < 1) {
return true; //Die silently? Don't know how to handle such case, please help...
// throw "Need two or more arguments to compare";
}
for (i = 1, l = arguments.length; i < l; i++) {
leftChain = []; //Todo: this can be cached
rightChain = [];
if (!compare2Objects(arguments[0], arguments[i])) {
return false;
}
}
return true;
}
Known issues (well, they have very low priority, probably you'll never notice them):
objects with different prototype structure but same projection
functions may have identical text but refer to different closures
Tests: passes tests are from How to determine equality for two JavaScript objects?.
Here is my ES3 commented solution (gory details after the code):
function object_equals( x, y ) {
if ( x === y ) return true;
// if both x and y are null or undefined and exactly the same
if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
// if they are not strictly equal, they both need to be Objects
if ( x.constructor !== y.constructor ) return false;
// they must have the exact same prototype chain, the closest we can do is
// test there constructor.
for ( var p in x ) {
if ( ! x.hasOwnProperty( p ) ) continue;
// other properties were tested using x.constructor === y.constructor
if ( ! y.hasOwnProperty( p ) ) return false;
// allows to compare x[ p ] and y[ p ] when set to undefined
if ( x[ p ] === y[ p ] ) continue;
// if they have the same strict value or identity then they are equal
if ( typeof( x[ p ] ) !== "object" ) return false;
// Numbers, Strings, Functions, Booleans must be strictly equal
if ( ! object_equals( x[ p ], y[ p ] ) ) return false;
// Objects and Arrays must be tested recursively
}
for ( p in y )
if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) )
return false;
// allows x[ p ] to be set to undefined
return true;
}
In developing this solution, I took a particular look at corner cases, efficiency, yet trying to yield a simple solution that works, hopefully with some elegance. JavaScript allows both null and undefined properties and objects have prototypes chains that can lead to very different behaviors if not checked.
First I have chosen to not extend Object.prototype, mostly because null could not be one of the objects of the comparison and that I believe that null should be a valid object to compare with another. There are also other legitimate concerns noted by others regarding the extension of Object.prototype regarding possible side effects on other's code.
Special care must taken to deal the possibility that JavaScript allows object properties can be set to undefined, i.e. there exists properties which values are set to undefined. The above solution verifies that both objects have the same properties set to undefined to report equality. This can only be accomplished by checking the existence of properties using Object.hasOwnProperty( property_name ). Also note that JSON.stringify() removes properties that are set to undefined, and that therefore comparisons using this form will ignore properties set to the value undefined.
Functions should be considered equal only if they share the same reference, not just the same code, because this would not take into account these functions prototype. So comparing the code string does not work to guaranty that they have the same prototype object.
The two objects should have the same prototype chain, not just the same properties. This can only be tested cross-browser by comparing the constructor of both objects for strict equality. ECMAScript 5 would allow to test their actual prototype using Object.getPrototypeOf(). Some web browsers also offer a __proto__ property that does the same thing. A possible improvement of the above code would allow to use one of these methods whenever available.
The use of strict comparisons is paramount here because 2 should not be considered equal to "2.0000", nor false should be considered equal to null, undefined, or 0.
Efficiency considerations lead me to compare for equality of properties as soon as possible. Then, only if that failed, look for the typeof these properties. The speed boost could be significant on large objects with lots of scalar properties.
No more that two loops are required, the first to check properties from the left object, the second to check properties from the right and verify only existence (not value), to catch these properties which are defined with the undefined value.
Overall this code handles most corner cases in only 16 lines of code (without comments).
Update (8/13/2015). I have implemented a better version, as the function value_equals() that is faster, handles properly corner cases such as NaN and 0 different than -0, optionally enforcing objects' properties order and testing for cyclic references, backed by more than 100 automated tests as part of the Toubkal project test suite.
Utils.compareObjects = function(o1, o2){
for(var p in o1){
if(o1.hasOwnProperty(p)){
if(o1[p] !== o2[p]){
return false;
}
}
}
for(var p in o2){
if(o2.hasOwnProperty(p)){
if(o1[p] !== o2[p]){
return false;
}
}
}
return true;
};
Simple way to compare ONE-LEVEL only objects.
Certainly not the only way - you could prototype a method (against Object here but I certainly wouldn't suggest using Object for live code) to replicate C#/Java style comparison methods.
Edit, since a general example seems to be expected:
Object.prototype.equals = function(x)
{
for(p in this)
{
switch(typeof(this[p]))
{
case 'object':
if (!this[p].equals(x[p])) { return false }; break;
case 'function':
if (typeof(x[p])=='undefined' || (p != 'equals' && this[p].toString() != x[p].toString())) { return false; }; break;
default:
if (this[p] != x[p]) { return false; }
}
}
for(p in x)
{
if(typeof(this[p])=='undefined') {return false;}
}
return true;
}
Note that testing methods with toString() is absolutely not good enough but a method which would be acceptable is very hard because of the problem of whitespace having meaning or not, never mind synonym methods and methods producing the same result with different implementations. And the problems of prototyping against Object in general.
The following algorithm will deal with self-referential data structures, numbers, strings, dates, and of course plain nested javascript objects:
Objects are considered equivalent when
They are exactly equal per === (String and Number are unwrapped first to ensure 42 is equivalent to Number(42))
or they are both dates and have the same valueOf()
or they are both of the same type and not null and...
they are not objects and are equal per == (catches numbers/strings/booleans)
or, ignoring properties with undefined value they have the same properties all of which are considered recursively equivalent.
Functions are not considered identical by function text. This test is insufficient because functions may have differing closures. Functions are only considered equal if === says so (but you could easily extend that equivalent relation should you choose to do so).
Infinite loops, potentially caused by circular datastructures, are avoided. When areEquivalent attempts to disprove equality and recurses into an object's properties to do so, it keeps track of the objects for which this sub-comparison is needed. If equality can be disproved, then some reachable property path differs between the objects, and then there must be a shortest such reachable path, and that shortest reachable path cannot contain cycles present in both paths; i.e. it is OK to assume equality when recursively comparing objects. The assumption is stored in a property areEquivalent_Eq_91_2_34, which is deleted after use, but if the object graph already contains such a property, behavior is undefined. The use of such a marker property is necessary because javascript doesn't support dictionaries using arbitrary objects as keys.
function unwrapStringOrNumber(obj) {
return (obj instanceof Number || obj instanceof String
? obj.valueOf()
: obj);
}
function areEquivalent(a, b) {
a = unwrapStringOrNumber(a);
b = unwrapStringOrNumber(b);
if (a === b) return true; //e.g. a and b both null
if (a === null || b === null || typeof (a) !== typeof (b)) return false;
if (a instanceof Date)
return b instanceof Date && a.valueOf() === b.valueOf();
if (typeof (a) !== "object")
return a == b; //for boolean, number, string, xml
var newA = (a.areEquivalent_Eq_91_2_34 === undefined),
newB = (b.areEquivalent_Eq_91_2_34 === undefined);
try {
if (newA) a.areEquivalent_Eq_91_2_34 = [];
else if (a.areEquivalent_Eq_91_2_34.some(
function (other) { return other === b; })) return true;
if (newB) b.areEquivalent_Eq_91_2_34 = [];
else if (b.areEquivalent_Eq_91_2_34.some(
function (other) { return other === a; })) return true;
a.areEquivalent_Eq_91_2_34.push(b);
b.areEquivalent_Eq_91_2_34.push(a);
var tmp = {};
for (var prop in a)
if(prop != "areEquivalent_Eq_91_2_34")
tmp[prop] = null;
for (var prop in b)
if (prop != "areEquivalent_Eq_91_2_34")
tmp[prop] = null;
for (var prop in tmp)
if (!areEquivalent(a[prop], b[prop]))
return false;
return true;
} finally {
if (newA) delete a.areEquivalent_Eq_91_2_34;
if (newB) delete b.areEquivalent_Eq_91_2_34;
}
}
I wrote this piece of code for object comparison, and it seems to work. check the assertions:
function countProps(obj) {
var count = 0;
for (k in obj) {
if (obj.hasOwnProperty(k)) {
count++;
}
}
return count;
};
function objectEquals(v1, v2) {
if (typeof(v1) !== typeof(v2)) {
return false;
}
if (typeof(v1) === "function") {
return v1.toString() === v2.toString();
}
if (v1 instanceof Object && v2 instanceof Object) {
if (countProps(v1) !== countProps(v2)) {
return false;
}
var r = true;
for (k in v1) {
r = objectEquals(v1[k], v2[k]);
if (!r) {
return false;
}
}
return true;
} else {
return v1 === v2;
}
}
assert.isTrue(objectEquals(null,null));
assert.isFalse(objectEquals(null,undefined));
assert.isTrue(objectEquals("hi","hi"));
assert.isTrue(objectEquals(5,5));
assert.isFalse(objectEquals(5,10));
assert.isTrue(objectEquals([],[]));
assert.isTrue(objectEquals([1,2],[1,2]));
assert.isFalse(objectEquals([1,2],[2,1]));
assert.isFalse(objectEquals([1,2],[1,2,3]));
assert.isTrue(objectEquals({},{}));
assert.isTrue(objectEquals({a:1,b:2},{a:1,b:2}));
assert.isTrue(objectEquals({a:1,b:2},{b:2,a:1}));
assert.isFalse(objectEquals({a:1,b:2},{a:1,b:3}));
assert.isTrue(objectEquals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}},{1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}));
assert.isFalse(objectEquals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}},{1:{name:"mhc",age:28}, 2:{name:"arb",age:27}}));
assert.isTrue(objectEquals(function(x){return x;},function(x){return x;}));
assert.isFalse(objectEquals(function(x){return x;},function(y){return y+2;}));
I have modified a bit the code above. for me 0 !== false and null !== undefined. If you do not need such strict check remove one "=" sign in "this[p] !== x[p]" inside the code.
Object.prototype.equals = function(x){
for (var p in this) {
if(typeof(this[p]) !== typeof(x[p])) return false;
if((this[p]===null) !== (x[p]===null)) return false;
switch (typeof(this[p])) {
case 'undefined':
if (typeof(x[p]) != 'undefined') return false;
break;
case 'object':
if(this[p]!==null && x[p]!==null && (this[p].constructor.toString() !== x[p].constructor.toString() || !this[p].equals(x[p]))) return false;
break;
case 'function':
if (p != 'equals' && this[p].toString() != x[p].toString()) return false;
break;
default:
if (this[p] !== x[p]) return false;
}
}
return true;
}
Then I have tested it with next objects:
var a = {a: 'text', b:[0,1]};
var b = {a: 'text', b:[0,1]};
var c = {a: 'text', b: 0};
var d = {a: 'text', b: false};
var e = {a: 'text', b:[1,0]};
var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
var i = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var j = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var k = {a: 'text', b: null};
var l = {a: 'text', b: undefined};
a==b expected true; returned true
a==c expected false; returned false
c==d expected false; returned false
a==e expected false; returned false
f==g expected true; returned true
h==g expected false; returned false
i==j expected true; returned true
d==k expected false; returned false
k==l expected false; returned false
Here is my version, pretty much stuff from this thread is integrated (same counts for the test cases):
Object.defineProperty(Object.prototype, "equals", {
enumerable: false,
value: function (obj) {
var p;
if (this === obj) {
return true;
}
// some checks for native types first
// function and sring
if (typeof(this) === "function" || typeof(this) === "string" || this instanceof String) {
return this.toString() === obj.toString();
}
// number
if (this instanceof Number || typeof(this) === "number") {
if (obj instanceof Number || typeof(obj) === "number") {
return this.valueOf() === obj.valueOf();
}
return false;
}
// null.equals(null) and undefined.equals(undefined) do not inherit from the
// Object.prototype so we can return false when they are passed as obj
if (typeof(this) !== typeof(obj) || obj === null || typeof(obj) === "undefined") {
return false;
}
function sort (o) {
var result = {};
if (typeof o !== "object") {
return o;
}
Object.keys(o).sort().forEach(function (key) {
result[key] = sort(o[key]);
});
return result;
}
if (typeof(this) === "object") {
if (Array.isArray(this)) { // check on arrays
return JSON.stringify(this) === JSON.stringify(obj);
} else { // anyway objects
for (p in this) {
if (typeof(this[p]) !== typeof(obj[p])) {
return false;
}
if ((this[p] === null) !== (obj[p] === null)) {
return false;
}
switch (typeof(this[p])) {
case 'undefined':
if (typeof(obj[p]) !== 'undefined') {
return false;
}
break;
case 'object':
if (this[p] !== null
&& obj[p] !== null
&& (this[p].constructor.toString() !== obj[p].constructor.toString()
|| !this[p].equals(obj[p]))) {
return false;
}
break;
case 'function':
if (this[p].toString() !== obj[p].toString()) {
return false;
}
break;
default:
if (this[p] !== obj[p]) {
return false;
}
}
};
}
}
// at least check them with JSON
return JSON.stringify(sort(this)) === JSON.stringify(sort(obj));
}
});
Here is my TestCase:
assertFalse({}.equals(null));
assertFalse({}.equals(undefined));
assertTrue("String", "hi".equals("hi"));
assertTrue("Number", new Number(5).equals(5));
assertFalse("Number", new Number(5).equals(10));
assertFalse("Number+String", new Number(1).equals("1"));
assertTrue([].equals([]));
assertTrue([1,2].equals([1,2]));
assertFalse([1,2].equals([2,1]));
assertFalse([1,2].equals([1,2,3]));
assertTrue(new Date("2011-03-31").equals(new Date("2011-03-31")));
assertFalse(new Date("2011-03-31").equals(new Date("1970-01-01")));
assertTrue({}.equals({}));
assertTrue({a:1,b:2}.equals({a:1,b:2}));
assertTrue({a:1,b:2}.equals({b:2,a:1}));
assertFalse({a:1,b:2}.equals({a:1,b:3}));
assertTrue({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}));
assertFalse({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:27}}));
assertTrue("Function", (function(x){return x;}).equals(function(x){return x;}));
assertFalse("Function", (function(x){return x;}).equals(function(y){return y+2;}));
var a = {a: 'text', b:[0,1]};
var b = {a: 'text', b:[0,1]};
var c = {a: 'text', b: 0};
var d = {a: 'text', b: false};
var e = {a: 'text', b:[1,0]};
var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
var i = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var j = {
a: 'text',
c: {
b: [1, 0],
f: function(){
this.a = this.b;
}
}
};
var k = {a: 'text', b: null};
var l = {a: 'text', b: undefined};
assertTrue(a.equals(b));
assertFalse(a.equals(c));
assertFalse(c.equals(d));
assertFalse(a.equals(e));
assertTrue(f.equals(g));
assertFalse(h.equals(g));
assertTrue(i.equals(j));
assertFalse(d.equals(k));
assertFalse(k.equals(l));
If you work without the JSON library, maybe this will help you out:
Object.prototype.equals = function(b) {
var a = this;
for(i in a) {
if(typeof b[i] == 'undefined') {
return false;
}
if(typeof b[i] == 'object') {
if(!b[i].equals(a[i])) {
return false;
}
}
if(b[i] != a[i]) {
return false;
}
}
for(i in b) {
if(typeof a[i] == 'undefined') {
return false;
}
if(typeof a[i] == 'object') {
if(!a[i].equals(b[i])) {
return false;
}
}
if(a[i] != b[i]) {
return false;
}
}
return true;
}
var a = {foo:'bar', bar: {blub:'bla'}};
var b = {foo:'bar', bar: {blub:'blob'}};
alert(a.equals(b)); // alert's a false
if you want to check for methods explicitly you can use the method.toSource() or method.toString() methods.

Categories