minBy.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. /**
  3. * Copyright (c) 2013-present, Facebook, Inc.
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. *
  8. *
  9. */
  10. var compareNumber = function compareNumber(a, b) {
  11. return a - b;
  12. };
  13. /**
  14. * Returns the minimum element as measured by a scoring function f. Returns the
  15. * first such element if there are ties.
  16. */
  17. function minBy(as, f, compare) {
  18. compare = compare || compareNumber;
  19. var minA = undefined;
  20. var minB = undefined;
  21. var seenFirst = false;
  22. var _iteratorNormalCompletion = true;
  23. var _didIteratorError = false;
  24. var _iteratorError = undefined;
  25. try {
  26. for (var _iterator = as[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  27. var a = _step.value;
  28. var b = f(a);
  29. if (!seenFirst || compare(b, minB) < 0) {
  30. minA = a;
  31. minB = b;
  32. seenFirst = true;
  33. }
  34. }
  35. } catch (err) {
  36. _didIteratorError = true;
  37. _iteratorError = err;
  38. } finally {
  39. try {
  40. if (!_iteratorNormalCompletion && _iterator["return"]) {
  41. _iterator["return"]();
  42. }
  43. } finally {
  44. if (_didIteratorError) {
  45. throw _iteratorError;
  46. }
  47. }
  48. }
  49. return minA;
  50. }
  51. module.exports = minBy;