minBy<S, T> function

S minBy <S, T>(Iterable<S> values, T orderBy(S element), { int compare(T value1, T value2) })

Returns the element of values for which orderBy returns the minimum value.

The values returned by orderBy are compared using the compare function. If compare is omitted, values must implement Comparable<T> and they are compared using their Comparable.compareTo.

Implementation

S minBy<S, T>(Iterable<S> values, T orderBy(S element),
    {int compare(T value1, T value2)}) {
  compare ??= defaultCompare<T>();

  S minValue;
  T minOrderBy;
  for (var element in values) {
    var elementOrderBy = orderBy(element);
    if (minOrderBy == null || compare(elementOrderBy, minOrderBy) < 0) {
      minValue = element;
      minOrderBy = elementOrderBy;
    }
  }
  return minValue;
}