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.

Implementation

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