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