minMax<T> static method

Pair<T>? minMax<T>(
  1. Iterable<T>? ns, [
  2. Comparator<T>? comparator
])

A pair with minimum and maximum value of ns entries.

comparator is optional and useful for non num T.

Implementation

static Pair<T>? minMax<T>(Iterable<T>? ns, [Comparator<T>? comparator]) {
  if (ns == null || ns.isEmpty) return null;

  if (comparator != null) {
    var min = ns.first;
    var max = min;

    for (var n in ns) {
      if (comparator(n, min) < 0) min = n;
      if (comparator(n, max) > 0) max = n;
    }

    return Pair<T>(min, max);
  } else {
    var min = ns.first as num;
    var max = min;

    for (var n in ns.map((e) => e as num)) {
      if (n < min) min = n;
      if (n > max) max = n;
    }

    return Pair<T>(min as T, max as T);
  }
}