minBy.js.flow 803 B

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule minBy
  8. * @flow
  9. */
  10. var compareNumber = (a, b) => a - b;
  11. /**
  12. * Returns the minimum element as measured by a scoring function f. Returns the
  13. * first such element if there are ties.
  14. */
  15. function minBy<A, B>(as: Iterable<A>, f: (a: A) => B, compare?: ?(u: B, v: B) => number): ?A {
  16. compare = compare || (compareNumber: any);
  17. var minA = undefined;
  18. var minB = undefined;
  19. var seenFirst = false;
  20. for (var a of as) {
  21. var b = f(a);
  22. if (!seenFirst || compare(b, (minB: any)) < 0) {
  23. minA = a;
  24. minB = b;
  25. seenFirst = true;
  26. }
  27. }
  28. return minA;
  29. }
  30. module.exports = minBy;