Max method

T Max ([EqualityComparer<T> comparer ])

Returns the maximum value in the enumerable.

Iterates over the enumerable and applies the sorter property of the given EqualityComparer to each element in order to find the maximum value. Once iteration is complete, Max will return the largest element found.

When the type of the enumerable is one of the below types, the EqualityComparer can be omitted. In this case, the function defaults to predefined maximum functions depending on the type:

  • Numeric types (num, int, double) return the maximum of all elements as defined by the max function in dart:math.
  • String types return the alphabetic maximum of all elements.

If the enumerable type is not one of these types, the EqualityComparer must be provided. Otherwise, an ArgumentError will be thrown.

If the enumerable is empty, an EmptyEnumerableError will be thrown.

The Max function will iterate over every element in the enumerable.

Implementation

T Max([EqualityComparer<T> comparer]) {
  if (comparer == null && T != num && T != int && T != double && T != String)
    throw ArgumentError(
        '`comparer` must not be null or the type of this enumerable must be one of the following: ${[
      num,
      int,
      double,
      String
    ]}');

  if (comparer == null) {
    if (T == num)
      return EnumerableReducers.MaxNum(this as Enumerable<num>) as T;
    if (T == int)
      return EnumerableReducers.MaxInt(this as Enumerable<int>) as T;
    if (T == double)
      return EnumerableReducers.MaxDouble(this as Enumerable<double>) as T;
    if (T == String)
      return EnumerableReducers.MaxString(this as Enumerable<String>) as T;
    throw UnexpectedStateError();
  }

  final iterator = this.iterator;
  if (!iterator.moveNext()) throw EmptyEnumerableError();

  T max = null;
  do {
    if (max == null)
      max = iterator.current;
    else if (comparer.sort(max, iterator.current) < 0) {
      max = iterator.current;
    }
  } while (iterator.moveNext());

  return max;
}