Make _.size work consistently cross-browser with arguments objects and avoid erroring when falsey values are passed.

Former-commit-id: 76dc852a4e1fd84218f9c57f44c93e483a3680d9
This commit is contained in:
John-David Dalton
2012-06-26 03:23:53 -04:00
parent 911014db95
commit 65f8da1654
2 changed files with 20 additions and 5 deletions

View File

@@ -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;
}
/**

View File

@@ -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));
/*--------------------------------------------------------------------------*/