_createReduce.js 1.0 KB

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