intersection<T> function

Set<T> intersection<T>(
  1. Iterable<T> values,
  2. Iterable<Iterable<T>> others
)

Returns a new Set containing every distinct value in values that also appears in every iterable of others.

Implementation

// DIVERGES(d3-array): adapt-array-typed-api, returns native Dart Set<T> and
// takes Iterable<Iterable<T>> (plus intersection2 for two iterables).
Set<T> intersection<T>(Iterable<T> values, Iterable<Iterable<T>> others) {
  final base = <T>{};
  var baseHasNaN = false;
  for (final v in values) {
    if (_isNaN(v)) {
      if (!baseHasNaN) {
        baseHasNaN = true;
        base.add(v);
      }
    } else {
      base.add(v);
    }
  }
  final otherSets = <(Set<T>, bool)>[];
  for (final other in others) {
    final s = <T>{};
    var hasNaN = false;
    for (final v in other) {
      if (_isNaN(v)) {
        hasNaN = true;
      } else {
        s.add(v);
      }
    }
    otherSets.add((s, hasNaN));
  }
  final out = <T>{};
  for (final value in base) {
    final isNan = _isNaN(value);
    var keep = true;
    for (final (s, hasNaN) in otherSets) {
      if (isNan ? !hasNaN : !s.contains(value)) {
        keep = false;
        break;
      }
    }
    if (keep) out.add(value);
  }
  return out;
}