_extremum.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435
  1. define(['./identity', './_cb', './find'], function (identity, _cb, find) {
  2. // The general algorithm behind `_.min` and `_.max`. `compare` should return
  3. // `true` if its first argument is more extreme than (i.e., should be preferred
  4. // over) its second argument, `false` otherwise. `iteratee` and `context`, like
  5. // in other collection functions, let you map the actual values in `collection`
  6. // to the values to `compare`. `decide` is an optional customization point
  7. // which is only present for historical reasons; please don't use it, as it will
  8. // likely be removed in the future.
  9. function extremum(collection, compare, iteratee, context, decide) {
  10. decide || (decide = identity);
  11. // `extremum` is essentially a combined map+reduce with **two** accumulators:
  12. // `result` and `iterResult`, respectively the unmapped and the mapped version
  13. // corresponding to the same element.
  14. var result, iterResult;
  15. iteratee = _cb(iteratee, context);
  16. var first = true;
  17. find(collection, function(value, key) {
  18. var iterValue = iteratee(value, key, collection);
  19. if (first || compare(iterValue, iterResult)) {
  20. result = value;
  21. iterResult = iterValue;
  22. first = false;
  23. }
  24. });
  25. // `extremum` normally returns an unmapped element from `collection`. However,
  26. // `_.min` and `_.max` forcibly return a number even if there is no element
  27. // that maps to a numeric value. Passing both accumulators through `decide`
  28. // before returning enables this behavior.
  29. return decide(result, iterResult);
  30. }
  31. return extremum;
  32. });