From 65f8da165455ac629d55c105d2898f531b15d7c5 Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Tue, 26 Jun 2012 03:23:53 -0400 Subject: [PATCH] Make `_.size` work consistently cross-browser with `arguments` objects and avoid erroring when falsey values are passed. Former-commit-id: 76dc852a4e1fd84218f9c57f44c93e483a3680d9 --- lodash.js | 9 +++++---- test/test.js | 16 +++++++++++++++- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/lodash.js b/lodash.js index b89bd9582..4a0b2a72c 100644 --- a/lodash.js +++ b/lodash.js @@ -2918,10 +2918,11 @@ * // => 5 */ function size(value) { - var className = toString.call(value); - return className == arrayClass || className == stringClass - ? value.length - : keys(value).length; + if (!value) { + return 0; + } + var length = value.length; + return length === length >>> 0 ? value.length : keys(value).length; } /** diff --git a/test/test.js b/test/test.js index 9b09ab0ff..b5bf59f77 100644 --- a/test/test.js +++ b/test/test.js @@ -582,14 +582,28 @@ QUnit.module('lodash.size'); (function() { + var args = arguments; + test('should detect the size of a string value', function() { equal(_.size('abc'), 3); }); + test('should allow a falsey `object` argument', function() { + try { + var actual = [_.size(), _.size(null), _.size(false), _.size(0)]; + } catch(e) { } + + deepEqual(actual, [0, 0, 0, 0]); + }); + + test('should work with `arguments` objects (test in IE < 9)', function() { + equal(_.size(args), 3); + }); + test('fixes the JScript [[DontEnum]] bug (test in IE < 9)', function() { equal(_.size(shadowed), 7); }); - }()); + }(1, 2, 3)); /*--------------------------------------------------------------------------*/