From b0ed45b90438818fe07c4cb141d175d7dda2e52d Mon Sep 17 00:00:00 2001 From: C J Silverio Date: Thu, 12 Feb 2015 08:48:31 -0800 Subject: [PATCH 1/2] util: fixed behavior of isObject() This fixes issue #743. Brought the behavior of util.isObject() in line with expected behavior, inspired by utility libraries like underscore & lodash. In particular, it now returns true for functions, as expected. Added eight tests for isObject() to ensure it behaves as expected for a wide variety of input, including cases where it is expected to return false. --- lib/util.js | 3 ++- test/parallel/test-util.js | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/util.js b/lib/util.js index 86f585f95217e4..7a3d6b42cf9b93 100644 --- a/lib/util.js +++ b/lib/util.js @@ -543,7 +543,8 @@ function isRegExp(re) { exports.isRegExp = isRegExp; function isObject(arg) { - return arg !== null && typeof arg === 'object'; + var type = typeof arg; + return type === 'function' || type === 'object' && !!arg; } exports.isObject = isObject; diff --git a/test/parallel/test-util.js b/test/parallel/test-util.js index 2fb4bc5609bcd6..e3e33c96598152 100644 --- a/test/parallel/test-util.js +++ b/test/parallel/test-util.js @@ -50,6 +50,14 @@ assert.equal(true, util.isError(Object.create(Error.prototype))); // isObject assert.ok(util.isObject({}) === true); +assert.ok(util.isObject(function() {}) === true); +assert.ok(util.isObject([1, 2, 3]) === true); +assert.ok(util.isObject(new String('string')) === true); +assert.ok(util.isObject(null) === false); +assert.ok(util.isObject(undefined) === false); +assert.ok(util.isObject('string') === false); +assert.ok(util.isObject(42) === false); +assert.ok(util.isObject(true) === false); // isPrimitive assert.equal(false, util.isPrimitive({})); From aac9a5eb0a17cb8df2e510c693ca4e866856b573 Mon Sep 17 00:00:00 2001 From: C J Silverio Date: Thu, 12 Feb 2015 11:29:28 -0800 Subject: [PATCH 2/2] Perf tweak as suggested by @cjihrig Double negation considered slower than a straight null check. --- lib/util.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/util.js b/lib/util.js index 7a3d6b42cf9b93..090543a535c18b 100644 --- a/lib/util.js +++ b/lib/util.js @@ -544,7 +544,7 @@ exports.isRegExp = isRegExp; function isObject(arg) { var type = typeof arg; - return type === 'function' || type === 'object' && !!arg; + return type === 'function' || type === 'object' && arg !== null; } exports.isObject = isObject;