|
| 1 | +/** |
| 2 | + * |
| 3 | + reduce() exectues a provided *reducer* function on each element of |
| 4 | + the array returning a final single output value. |
| 5 | +
|
| 6 | + reduce() has two parameters: |
| 7 | +
|
| 8 | + - the reducer callback function |
| 9 | + - an initial value. If no initial value is supplied, the value |
| 10 | + of the first element in the array is used, and the initial |
| 11 | + iteration is skipped. |
| 12 | + (which will be the initial value of the accumulator) |
| 13 | +
|
| 14 | + The reducer function takes four arguments: |
| 15 | +
|
| 16 | + - the accumulator |
| 17 | + - the value of the current element |
| 18 | + - the index of the current element |
| 19 | + - the Array object being traversed |
| 20 | +
|
| 21 | + The return value of the reducer will be the new accumulator argument |
| 22 | + in the next iteration, and ultimately the final, single resulting value. |
| 23 | +
|
| 24 | + Calling reduce on an empty array without an initial value will trow a TypeError |
| 25 | +*/ |
| 26 | + |
| 27 | +Array.prototype.myReduce = function myReduce(reducer, initialValue) { |
| 28 | + let accumulator = initialValue; |
| 29 | + let i = 0; |
| 30 | + |
| 31 | + // initival value check |
| 32 | + if (typeof initialValue === 'undefined') { |
| 33 | + if (this.length === 0) { |
| 34 | + // no reduce on empty array without and initial value |
| 35 | + throw new TypeError('reduce on empty array without initial value'); |
| 36 | + } |
| 37 | + |
| 38 | + // no initial value, so accumulator is set to first element, |
| 39 | + // and first iteration is skipped |
| 40 | + [accumulator] = this; |
| 41 | + i = 1; |
| 42 | + } |
| 43 | + |
| 44 | + for (; i < this.length; i += 1) { |
| 45 | + accumulator = reducer(accumulator, this[i], i, this); |
| 46 | + } |
| 47 | + |
| 48 | + return accumulator; |
| 49 | +}; |
0 commit comments