containsAll method

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

如果 other 中的每个元素也存在于 this 中,则返回 true

如果 collapseDuplicates 为 true,则元素只出现一次就算满足条件。

如果 collapseDuplicates 为 false, this 中元素的出现次数必须为大于或等于 other 中该元素的出现次数。

举例:

[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;
    if (countInThis < otherElementCounts[element]!) {
      return false;
    }
  }
  return true;
}