Ensure _.sum and _.sumBy return 0 for empty arrays. [closes #1883]

This commit is contained in:
John-David Dalton
2016-01-26 01:29:18 -08:00
parent 25c7c8b153
commit 7a8ef7aeb7
2 changed files with 14 additions and 5 deletions

View File

@@ -841,7 +841,7 @@
result = result === undefined ? current : (result + current);
}
}
return result;
return length ? result : 0;
}
/**
@@ -13917,7 +13917,7 @@
function sum(array) {
return (array && array.length)
? baseSum(array, identity)
: undefined;
: 0;
}
/**
@@ -13945,7 +13945,7 @@
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, getIteratee(iteratee))
: undefined;
: 0;
}
/*------------------------------------------------------------------------*/

View File

@@ -12878,6 +12878,15 @@
var array = [4, 2, 8, 6];
assert.strictEqual(_.mean(array), 5);
});
QUnit.test('should return `NaN` when passing empty `array` values', function(assert) {
assert.expect(1);
var expected = lodashStable.map(empties, alwaysNaN),
actual = lodashStable.map(empties, _.mean);
assert.deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
@@ -18713,10 +18722,10 @@
assert.strictEqual(_.sum(array), 12);
});
QUnit.test('should return `undefined` when passing empty `array` values', function(assert) {
QUnit.test('should return `0` when passing empty `array` values', function(assert) {
assert.expect(1);
var expected = lodashStable.map(empties, alwaysUndefined),
var expected = lodashStable.map(empties, alwaysZero),
actual = lodashStable.map(empties, _.sum);
assert.deepEqual(actual, expected);