Skip to content

Commit b58a197

Browse files
committed
[BUGFIX beta] Fix EmberArray.reduce to match native behavior without initialValue
1 parent 288f730 commit b58a197

2 files changed

Lines changed: 40 additions & 4 deletions

File tree

packages/@ember/-internals/runtime/tests/array/reduce-test.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,31 @@ class ReduceTests extends AbstractTestCase {
1919
let res = obj.reduce((previousValue, item, index, enumerable) => enumerable, 0);
2020
this.assert.equal(res, obj);
2121
}
22+
23+
'@test works without an initialValue'() {
24+
let obj = this.newObject([1, 2, 3]);
25+
let res = obj.reduce((previousValue, item) => previousValue + item);
26+
this.assert.equal(res, 6);
27+
}
28+
29+
'@test passes correct index when without an initialValue'() {
30+
let obj = this.newObject([1, 2, 3]);
31+
let res = obj.reduce((previousValue, item, index) => previousValue + index);
32+
// starts at item 2 (index 1): 1 + 1 = 2
33+
// then item 3 (index 2): 2 + 2 = 4
34+
this.assert.equal(res, 4);
35+
}
36+
37+
'@test throws a TypeError when reducing an empty array without an initialValue'() {
38+
let obj = this.newObject([]);
39+
this.assert.throws(
40+
() => {
41+
obj.reduce((previousValue, item) => previousValue + item);
42+
},
43+
TypeError,
44+
'Reduce of empty array with no initial value'
45+
);
46+
}
2247
}
2348

2449
runArrayTests('reduce', ReduceTests);

packages/@ember/array/index.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1387,15 +1387,26 @@ const EmberArray = Mixin.create(Enumerable, {
13871387
reduce<T, V>(
13881388
this: EmberArray<T>,
13891389
callback: (summation: V, current: T, index: number, arr: EmberArray<T>) => V,
1390-
initialValue: V
1390+
initialValue?: V
13911391
) {
13921392
assert('`reduce` expects a function as first argument.', typeof callback === 'function');
13931393

1394-
let ret = initialValue;
1394+
let hasInitialValue = arguments.length > 1;
1395+
let ret: any = initialValue;
1396+
let startIndex = 0;
13951397

1396-
this.forEach(function (item, i) {
1398+
if (!hasInitialValue) {
1399+
if (this.length === 0) {
1400+
throw new TypeError('Reduce of empty array with no initial value');
1401+
}
1402+
ret = this.objectAt(0);
1403+
startIndex = 1;
1404+
}
1405+
1406+
for (let i = startIndex; i < this.length; i++) {
1407+
let item = this.objectAt(i) as T;
13971408
ret = callback(ret, item, i, this);
1398-
}, this);
1409+
}
13991410

14001411
return ret;
14011412
},

0 commit comments

Comments
 (0)