setIntersection<T> function

List<T> setIntersection<T>(
  1. Iterable<T> a,
  2. Iterable<T> b, {
  3. int compare(
    1. T,
    2. T
    )?,
})

Constructs a sorted intersection of elements from two sorted sequences a and b.

Both sequences must be sorted according to the same compare function. The resulting sequence contains only elements that are present in both a and b, keeping the sequence sorted.

Example:

final list1 = [1, 2, 4];
final list2 = [2, 3, 4];
final intersection = setIntersection(list1, list2); // Returns [2, 4]

Implementation

List<T> setIntersection<T>(
  Iterable<T> a,
  Iterable<T> b, {
  int Function(T, T)? compare,
}) {
  compare ??= _defaultCompare;
  var res = <T>[];
  var itA = a.iterator;
  var itB = b.iterator;
  bool hasA = itA.moveNext();
  bool hasB = itB.moveNext();

  while (hasA && hasB) {
    var comp = compare(itA.current, itB.current);
    if (comp < 0) {
      hasA = itA.moveNext();
    } else if (comp > 0) {
      hasB = itB.moveNext();
    } else {
      res.add(itA.current);
      hasA = itA.moveNext();
      hasB = itB.moveNext();
    }
  }
  return res;
}