setUnion<T> function

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

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

Both sequences must be sorted according to the same compare function. The resulting sequence contains all elements that are present in either a or b, keeping the sequence sorted. If an element exists in both, only the element from a is included.

Example:

final list1 = [1, 2, 4];
final list2 = [2, 3, 5];
final union = setUnion(list1, list2); // Returns [1, 2, 3, 4, 5]

Implementation

List<T> setUnion<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) {
      res.add(itA.current);
      hasA = itA.moveNext();
    } else if (comp > 0) {
      res.add(itB.current);
      hasB = itB.moveNext();
    } else {
      res.add(itA.current);
      hasA = itA.moveNext();
      hasB = itB.moveNext();
    }
  }
  while (hasA) {
    res.add(itA.current);
    hasA = itA.moveNext();
  }
  while (hasB) {
    res.add(itB.current);
    hasB = itB.moveNext();
  }
  return res;
}