correct size() impl for object's w/ 'length' prop

the original implementation returned incorrect value value for
objects with 'length' property.
This commit is contained in:
Igor Minar 2011-03-27 16:19:03 -07:00
parent 96a1df192a
commit a4863d5244
2 changed files with 14 additions and 8 deletions

View file

@ -487,17 +487,19 @@ function map(obj, iterator, context) {
*/ */
function size(obj, ownPropsOnly) { function size(obj, ownPropsOnly) {
var size = 0, key; var size = 0, key;
if (obj) {
if (isNumber(obj.length)) { if (isArray(obj) || isString(obj)) {
return obj.length; return obj.length;
} else if (isObject(obj)){ } else if (isObject(obj)){
for (key in obj) for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key)) if (!ownPropsOnly || obj.hasOwnProperty(key))
size++; size++;
}
} }
return size; return size;
} }
function includes(array, obj) { function includes(array, obj) {
for ( var i = 0; i < array.length; i++) { for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return true; if (obj === array[i]) return true;

View file

@ -133,6 +133,10 @@ describe('angular', function(){
expect(size('')).toBe(0); expect(size('')).toBe(0);
expect(size('abc')).toBe(3); expect(size('abc')).toBe(3);
}); });
it('should not rely on length property of an object to determine its size', function() {
expect(size({length:99})).toBe(1);
});
}); });