unique<T> function

Iterable<T> unique<T>(
  1. Iterable<T> src, [
  2. bool equals(
    1. T a,
    2. T b
    )?
])

Returns a new iterable with all duplicate elements removed.

The equals function is used to determine if two elements are equal. If it is not provided, the iterable's elements must be hashable and the == operator is used for equality checks.

The order of the elements in the returned iterable is the same as the order in which they appear in the original iterable.

Without equals the result is lazy: each iteration walks src afresh, so it can be iterated any number of times and reflects later changes to src. With equals the result is computed once, eagerly.

Implementation

Iterable<T> unique<T>(Iterable<T> src, [bool Function(T a, T b)? equals]) {
  if (equals == null) {
    return _uniqueByHash(src);
  } else {
    final uniqueList = <T>[];
    for (var element in src) {
      if (!uniqueList.any((existing) => equals(existing, element))) {
        uniqueList.add(element);
      }
    }
    return uniqueList;
  }
}