From 42487bf47dff4b0732977af2c6297b67ecec70af Mon Sep 17 00:00:00 2001 From: Dmitry Baranovskiy Date: Tue, 7 Jun 2011 09:48:34 +1000 Subject: [PATCH] Fixed isEqual if second object has isEqual implemented and added isObject method --- test/objects.js | 17 +++++++++++++++++ underscore.js | 6 ++++++ 2 files changed, 23 insertions(+) diff --git a/test/objects.js b/test/objects.js index 93c441176..48971c079 100644 --- a/test/objects.js +++ b/test/objects.js @@ -77,6 +77,8 @@ $(document).ready(function() { ok(_.isEqual(new Date(100), new Date(100)), 'identical dates are equal'); ok(_.isEqual((/hello/ig), (/hello/ig)), 'identical regexes are equal'); ok(!_.isEqual(null, [1]), 'a falsy is never equal to a truthy'); + ok(_.isEqual({isEqual: function () { return true; }}, {}), 'first object implements `isEqual`'); + ok(_.isEqual({}, {isEqual: function () { return true; }}), 'second object implements `isEqual`'); ok(!_.isEqual({x: 1, y: undefined}, {x: 1, z: 2}), 'objects with the same number of undefined keys are not equal'); ok(!_.isEqual(_({x: 1, y: undefined}).chain(), _({x: 1, z: 2}).chain()), 'wrapped objects are not equal'); equals(_({x: 1, y: 2}).chain().isEqual(_({x: 1, y: 2}).chain()).value(), true, 'wrapped objects are equal'); @@ -136,6 +138,21 @@ $(document).ready(function() { ok(_.isArguments(iArguments), 'even from another frame'); }); + test("objects: isObject", function() { + ok(_.isObject(arguments), 'the arguments object is object'); + ok(_.isObject([1, 2, 3]), 'and arrays'); + ok(_.isObject($('html')[0]), 'and DOM element'); + ok(_.isObject(iElement), 'even from another frame'); + ok(_.isObject(function () {}), 'and functions'); + ok(_.isObject(iFunction), 'even from another frame'); + ok(!_.isObject(null), 'but not null'); + ok(!_.isObject(undefined), 'and not undefined'); + ok(!_.isObject('string'), 'and not string'); + ok(!_.isObject(12), 'and not number'); + ok(!_.isObject(true), 'and not boolean'); + ok(_.isObject(new String('string')), 'but new String()'); + }); + test("objects: isArray", function() { ok(!_.isArray(arguments), 'the arguments object is not an array'); ok(_.isArray([1, 2, 3]), 'but arrays are'); diff --git a/underscore.js b/underscore.js index 84fc889ee..61fdb6ed5 100644 --- a/underscore.js +++ b/underscore.js @@ -600,6 +600,7 @@ if (b._chain) b = b._wrapped; // One of them implements an isEqual()? if (a.isEqual) return a.isEqual(b); + if (b.isEqual) return b.isEqual(a); // Check dates' integer values. if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime(); // Both are NaN? @@ -641,6 +642,11 @@ return toString.call(obj) === '[object Array]'; }; + // Is a given variable an object? + _.isObject = function(obj) { + return obj === Object(obj); + }; + // Is a given variable an arguments object? _.isArguments = function(obj) { return !!(obj && hasOwnProperty.call(obj, 'callee'));