containsAll method

bool containsAll(
  1. Iterable<E> other, {
  2. bool collapseDuplicates = true,
})

Returns true if every element in other also exists in this.

Example:

[1, 2, 3].containsAll([1, 2]); // true
[1, 2].containsAll([1, 2, 3]); // false

If collapseDuplicates is true, only the presence of a value will be considered, not the number of times it occurs. If collapseDuplicates is false, the number of occurrences of a given value in this must be greater than or equal to the number of occurrences of that value in other for the result to be true.

Example:

[1, 2, 3].containsAll([1, 1, 1, 2]); // true
[1, 2, 3].containsAll([1, 1, 1, 2], collapseDuplicates: false); // false
[1, 1, 2, 3].containsAll([1, 1, 2], collapseDuplicates: false); // true

Implementation

bool containsAll(Iterable<E> other, {bool collapseDuplicates = true}) {
  if (other.isEmpty) return true;
  if (collapseDuplicates) {
    return Set<E>.from(this).containsAll(Set<E>.from(other));
  }

  final thisElementCounts = _elementCountsIn<E>(this);
  final otherElementCounts = _elementCountsIn<E>(other);

  for (final element in otherElementCounts.keys) {
    final countInThis = thisElementCounts[element] ?? 0;
    final countInOther = otherElementCounts[element] ?? 0;
    if (countInThis < countInOther) {
      return false;
    }
  }
  return true;
}