diff --git a/test/collections.js b/test/collections.js index 90cdd3d87..cf1c815d6 100644 --- a/test/collections.js +++ b/test/collections.js @@ -177,6 +177,9 @@ $(document).ready(function() { var neg = _.max([1, 2, 3], function(num){ return -num; }); equals(neg, 1, 'can perform a computation-based max'); + + equals(-Infinity, _.max({}), 'Maximum value of an empty object'); + equals(-Infinity, _.max([]), 'Maximum value of an empty array'); }); test('collections: min', function() { @@ -184,6 +187,9 @@ $(document).ready(function() { var neg = _.min([1, 2, 3], function(num){ return -num; }); equals(neg, 3, 'can perform a computation-based min'); + + equals(Infinity, _.min({}), 'Minimum value of an empty object'); + equals(Infinity, _.min([]), 'Minimum value of an empty array'); }); test('collections: sortBy', function() { diff --git a/underscore.js b/underscore.js index f59d040c7..0db66d0b6 100644 --- a/underscore.js +++ b/underscore.js @@ -220,6 +220,7 @@ // Return the maximum element or (element-based computation). _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj); + if (!iterator && _.isEmpty(obj)) return -Infinity; var result = {computed : -Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; @@ -231,6 +232,7 @@ // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj); + if (!iterator && _.isEmpty(obj)) return Infinity; var result = {computed : Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value;