equalValue<T, K> function

K? equalValue<T, K>(
  1. Iterable<T> items,
  2. K? getValue(
    1. T a
    ), {
  3. bool equalityCheck(
    1. K? a,
    2. K? b
    )?,
})

Checks that all the retrieved values for an item are the same. If they're the same, it returns the equal value, otherwise it'll return null. A custom equalityCheck can be provided for objects that don't override their equality operator or need more sophisticated rules of equality (for example if your K is a collection). TODO: have two functions; one to check is all are equal, another to get the value?

Implementation

K? equalValue<T, K>(Iterable<T> items, K? Function(T a) getValue,
    {bool Function(K? a, K? b)? equalityCheck}) {
  if (items.isEmpty) {
    return null;
  }

  var iterator = items.iterator;
  // Move to first value.
  iterator.moveNext();
  K? value = getValue(iterator.current);

  // A little more verbose to wrap the loop with the conditional but more
  // efficient at runtime.
  if (equalityCheck != null) {
    while (iterator.moveNext()) {
      if (!equalityCheck(value, getValue(iterator.current))) {
        return null;
      }
    }
  } else {
    while (iterator.moveNext()) {
      if (value != getValue(iterator.current)) {
        return null;
      }
    }
  }
  return value;
}