encloses method

  1. @override
  2. @useResult
bool encloses(
  1. Range<T> other
)
override

Returns true if other's bounds do not extend outside this bounds.

It is not possible for an Interval to enclose a Min or Max. Neither is it possible for a Min to enclose a Max and vice versa.

A discrete range is not considered to be enclosed by another under certain circumstances, i.e. [4..5] does not enclose (3..6).

A Range that encloses another Range always intersects.

This method is reflexive, anti-symmetric and transitive.

Examples

final a = Interval.closed(1, 4);
final b = Interval.closedOpen(2, 3);

a.encloses(b); // true, [1..4] encloses [2..3]
final a = Interval.open(1, 4);
final b = Interval.open(1, 4);

a.encloses(b); // true, (1..4) encloses (1..4)
final a = Interval.open(1, 4);
final b = Interval.closedOpen(2, 2);

a.encloses(b); // true, (1..4) encloses [2..2)
final a = Interval.openClosed(3, 6);
final b = Interval.openClosed(2, 8);

a.encloses(b); // false, (3..6] does not enclose (2..8]
final a = Interval.openClosed(3, 6);
final b = Interval.closed(3, 6);

a.encloses(b); // false, (3..6] does not enclose [3..6]
final a = Interval.closed(4, 5);
final b = Interval.open(3, 6);

a.encloses(b); // false, [4..5] does not enclose (3..6), discrete range
final a = Interval.openClosed(3, 6);
final b = Interval.closedOpen(1, 1);

a.encloses(b); // false, (3..6] does not enclose (1..1]

Implementation

@override
@useResult bool encloses(Range<T> other) {
  switch (other) {
    case Max<T> _:
      final comparison = other.value.compareTo(value);
      return (comparison < 0) || (comparison == 0 && (closed || other.open));

    case Interval<T> _:
      final comparison = other.max.value.compareTo(value);
      return (comparison < 0) || (comparison == 0 && (closed || other.max.open));

    default:
      return false;
  }
}