minBy<S, T> function Null safety

S? minBy<S, T>(
  1. Iterable<S> values,
  2. T orderBy(
    1. S
    ),
  3. {int compare(
    1. T,
    2. T
    )?}
)

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.

Returns null if values is empty.

Implementation

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

  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;
}