difference method

Iterable<Interval>? difference(
  1. Interval other
)

Returns the difference between this interval and the other interval, or null if the other interval contains this interval.

In other words, the returned iterable contains the interval(s) that are not in the other interval.

final a = Interval(0, 3);
final b = Interval(2, 5);
print(a.difference(b)); // [[0, 2]]
print(b.difference(a)); // [[3, 5]]

Notice that a.difference(b) != b.difference(a).

The returned iterable may contain multiple intervals if removing the other interval splits the remaining interval, or null if there is no interval left after removing the other interval.

final a = Interval(1, 5);
final b = Interval(2, 4);
print(a.difference(b)); // [[1, 2], [4, 5]]
print(b.difference(a)); // null

Implementation

Iterable<Interval>? difference(Interval other) {
  if (other.contains(this)) return null;
  if (!other.intersects(this)) return [this];
  if (other.start > start && other.end >= end) {
    return [Interval(start, other.start)];
  }
  if (other.start <= start && other.end < end) {
    return [Interval(other.end, end)];
  }
  return [Interval(start, other.start), Interval(other.end, end)];
}