between method

bool between (
  1. T minimum,
  2. T maximum,
  3. {int sorter(
    1. T value,
    2. T element
    ),
  4. bool minimumInclusive: false,
  5. bool maximumInclusive: false}
)

Returns true if all elements in the iterable are between minimum and maximum.

Iterates over the entire iterable and uses a sorting function to compare value to each element in the iterable. If any element is not between minimum and maximum, this method returns false. Otherwise, if every element is less than or equal to value, this method returns true.

Exclusivity on this method is controlled by the minimumInclusive and maximumInclusive parameters. These parameters default to true.

If sorter is omitted, the method checks EqualityComparer.forType to see if a default sorting function exists. If one is found, it is used. If one is not found, this method throws an ArgumentError.

If this iterable is empty, a StateError is thrown.

Implementation

bool between(
  T minimum,
  T maximum, {
  int Function(T value, T element) sorter,
  bool minimumInclusive = false,
  bool maximumInclusive = false,
}) {
  checkNullError(this);

  sorter ??= EqualityComparer.forType<T>()?.sort;
  if (sorter == null) {
    throw ArgumentError.notNull('sorter');
  }

  final iterator = this.iterator;
  if (!iterator.moveNext()) {
    throw StateError('Cannot call "between" on an empty iterable.');
  }

  do {
    final minCompare = sorter(minimum, iterator.current);
    final maxCompare = sorter(maximum, iterator.current);
    if (minCompare > 0 ||
        (!minimumInclusive && minCompare == 0) ||
        maxCompare < 0 ||
        (!maximumInclusive && maxCompare == 0)) {
      return false;
    }
  } while (iterator.moveNext());

  return true;
}