UNPKG

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