1 | var aFunction = require('../internals/a-function');
|
---|
2 | var toObject = require('../internals/to-object');
|
---|
3 | var IndexedObject = require('../internals/indexed-object');
|
---|
4 | var toLength = require('../internals/to-length');
|
---|
5 |
|
---|
6 | // `Array.prototype.{ reduce, reduceRight }` methods implementation
|
---|
7 | var createMethod = function (IS_RIGHT) {
|
---|
8 | return function (that, callbackfn, argumentsLength, memo) {
|
---|
9 | aFunction(callbackfn);
|
---|
10 | var O = toObject(that);
|
---|
11 | var self = IndexedObject(O);
|
---|
12 | var length = toLength(O.length);
|
---|
13 | var index = IS_RIGHT ? length - 1 : 0;
|
---|
14 | var i = IS_RIGHT ? -1 : 1;
|
---|
15 | if (argumentsLength < 2) while (true) {
|
---|
16 | if (index in self) {
|
---|
17 | memo = self[index];
|
---|
18 | index += i;
|
---|
19 | break;
|
---|
20 | }
|
---|
21 | index += i;
|
---|
22 | if (IS_RIGHT ? index < 0 : length <= index) {
|
---|
23 | throw TypeError('Reduce of empty array with no initial value');
|
---|
24 | }
|
---|
25 | }
|
---|
26 | for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
|
---|
27 | memo = callbackfn(memo, self[index], index, O);
|
---|
28 | }
|
---|
29 | return memo;
|
---|
30 | };
|
---|
31 | };
|
---|
32 |
|
---|
33 | module.exports = {
|
---|
34 | // `Array.prototype.reduce` method
|
---|
35 | // https://tc39.es/ecma262/#sec-array.prototype.reduce
|
---|
36 | left: createMethod(false),
|
---|
37 | // `Array.prototype.reduceRight` method
|
---|
38 | // https://tc39.es/ecma262/#sec-array.prototype.reduceright
|
---|
39 | right: createMethod(true)
|
---|
40 | };
|
---|