maxBy<T extends Comparable<Object>> method Null safety

E? maxBy<T extends Comparable<Object>>(
  1. T selector(
    1. int index,
    2. E
    )
)

Returns the first element yielding the largest value of the given function or null if there are no elements.

For example:

[-3, 2].maxBy((_, x) => x * x) // => -3

Implementation

E? maxBy<T extends Comparable<Object>>(T Function(int index, E) selector) {
  E? maxElem;
  T? maxValue;

  forEachIndexed((i, e) {
    final v = selector(i, e);
    if (maxValue == null || v.compareTo(maxValue!) > 0) {
      maxValue = v;
      maxElem = e;
    }
  });

  return maxElem;
}