_createReduce.js 1.1 KB

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