intersection method

  1. @override
  2. @useResult
Range<T>? intersection(
  1. Range<T> other
)
override

If this intersects other, returns the intersection. Otherwise returns null.

See intersects for determining if two ranges intersect.

final foo = Interval.open(1, 5);
final bar = Interval.closed(3, 7);

foo.intersection(bar); // [3..5), { x | 3 <= x < 5 }


Min.open(5).intersection(Min.closed(7)); // [7..+∞)

Max.open(5).intersection(Max.closed(7)); // (-∞..5)

Interval.open(1, 5).intersection(Interval.open(7, 9)); // null

Implementation

@override
@useResult Range<T>? intersection(Range<T> other) => switch (other) {
  Min<T> _ => switch (value.compareTo(other.value)) {
    < 0 when other.open => Min.open(other.value),
    < 0 when other.closed => Min.closed(other.value),
    > 0 when open => Min.open(value),
    > 0 when closed => Min.closed(value),
    _ when open || other.open => Min.open(value),
    _ => Min.closed(value),
  },
  Interval<T> _ => Intersections.minInterval(this, other),
  Max<T> _ => Intersections.minMax(this, other),
  Unbound<T> _ => this,
};