_createReduce.js 1.0 KB

123456789101112131415161718192021222324252627282930
  1. var _isArrayLike = require('./_isArrayLike.js');
  2. var keys = require('./keys.js');
  3. var _optimizeCb = require('./_optimizeCb.js');
  4. // Internal helper to create a reducing function, iterating left or right.
  5. 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. }
  27. module.exports = createReduce;