| 1 | import isArrayLike from './_isArrayLike.js';
|
|---|
| 2 | import keys from './keys.js';
|
|---|
| 3 | import optimizeCb from './_optimizeCb.js';
|
|---|
| 4 |
|
|---|
| 5 | // Internal helper to create a reducing function, iterating left or right.
|
|---|
| 6 | export default function createReduce(dir) {
|
|---|
| 7 | // Wrap code that reassigns argument variables in a separate function than
|
|---|
| 8 | // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
|
|---|
| 9 | var reducer = function(obj, iteratee, memo, initial) {
|
|---|
| 10 | var _keys = !isArrayLike(obj) && keys(obj),
|
|---|
| 11 | length = (_keys || obj).length,
|
|---|
| 12 | index = dir > 0 ? 0 : length - 1;
|
|---|
| 13 | if (!initial) {
|
|---|
| 14 | memo = obj[_keys ? _keys[index] : index];
|
|---|
| 15 | index += dir;
|
|---|
| 16 | }
|
|---|
| 17 | for (; index >= 0 && index < length; index += dir) {
|
|---|
| 18 | var currentKey = _keys ? _keys[index] : index;
|
|---|
| 19 | memo = iteratee(memo, obj[currentKey], currentKey, obj);
|
|---|
| 20 | }
|
|---|
| 21 | return memo;
|
|---|
| 22 | };
|
|---|
| 23 |
|
|---|
| 24 | return function(obj, iteratee, memo, context) {
|
|---|
| 25 | var initial = arguments.length >= 3;
|
|---|
| 26 | return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
|
|---|
| 27 | };
|
|---|
| 28 | }
|
|---|