iterableEquals<T> function

bool iterableEquals<T>(
  1. Iterable<T>? list1,
  2. Iterable<T>? list2, {
  3. bool equalityCheck(
    1. T a,
    2. T b
    )?,
})

Check if an iterable is equal to another iterable. Iterables are considered equal if they have the same number of values and each of those values are equal. A custom equalityCheck can be provided for objects that don't override their equality operator or need to be deemed equal based on varying application logic.

Implementation

bool iterableEquals<T>(Iterable<T>? list1, Iterable<T>? list2,
    {bool Function(T a, T b)? equalityCheck}) {
  if (list1 == null || list2 == null) {
    return false;
  }
  if (identical(list1, list2)) return true;
  int length = list1.length;
  if (length != list2.length) return false;

  var a = list1.iterator;
  var b = list2.iterator;
  // A little more verbose to wrap the loop with the conditional but more
  // efficient at runtime.
  if (equalityCheck != null) {
    // Iterator starts at null current value, must be moved to first value.
    while (a.moveNext() && b.moveNext()) {
      if (!equalityCheck(a.current, b.current)) {
        return false;
      }
    }
  } else {
    // Iterator starts at null current value, must be moved to first value.
    while (a.moveNext() && b.moveNext()) {
      if (a.current != b.current) {
        return false;
      }
    }
  }

  return true;
}