1 |
|
2 |
|
3 | |
4 |
|
5 |
|
6 | function reduce(arr, fn, initVal) {
|
7 |
|
8 | var hasInit = arguments.length > 2,
|
9 | result = initVal;
|
10 |
|
11 | if (arr == null || !arr.length) {
|
12 | if (!hasInit) {
|
13 | throw new Error('reduce of empty array with no initial value');
|
14 | } else {
|
15 | return initVal;
|
16 | }
|
17 | }
|
18 |
|
19 | var i = -1, len = arr.length;
|
20 | while (++i < len) {
|
21 | if (!hasInit) {
|
22 | result = arr[i];
|
23 | hasInit = true;
|
24 | } else {
|
25 | result = fn(result, arr[i], i, arr);
|
26 | }
|
27 | }
|
28 |
|
29 | return result;
|
30 | }
|
31 |
|
32 | module.exports = reduce;
|
33 |
|