-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathreduceRight.js
35 lines (30 loc) · 959 Bytes
/
reduceRight.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
'use strict';
var bindInternal4 = require('../function/bindInternal4');
/**
* # Reduce Right
*
* A fast `.reduceRight()` implementation.
*
* @param {Array} subject The array (or array-like) to reduce.
* @param {Function} fn The reducer function.
* @param {mixed} initialValue The initial value for the reducer, defaults to subject[0].
* @param {Object} thisContext The context for the reducer.
* @return {mixed} The final result.
*/
module.exports = function fastReduce (subject, fn, initialValue, thisContext) {
var length = subject.length,
iterator = thisContext !== undefined ? bindInternal4(fn, thisContext) : fn,
i, result;
if (initialValue === undefined) {
i = length - 2;
result = subject[length - 1];
}
else {
i = length - 1;
result = initialValue;
}
for (; i >= 0; i--) {
result = iterator(result, subject[i], i, subject);
}
return result;
};