containsInOrder method

void containsInOrder(
  1. Iterable<Object?> elements
)

Expects that the iterable contains a value matching each expected value from elelements in the given order, with any extra elements between them.

For example, the following will succeed:

check([1, 0, 2, 0, 3]).containsInOrder([1, 2, 3]);

Values in elements may be a T, a Condition<T>, or a Condition<Object?>. If an expectation is a condition callback it will be checked against the actual values, and any other expectations, including those that are not a T or a condition callback, will be compared with the equality operator.

check([1, 0, 2, 0, 3])
  .containsInOrder([1, (Subject<int> v) => v.isGreaterThan(1), 3]);

Implementation

void containsInOrder(Iterable<Object?> elements) {
  context.expect(() => prefixFirst('contains, in order: ', literal(elements)),
      (actual) {
    final expected = elements.toList();
    if (expected.isEmpty) {
      throw ArgumentError('expected may not be empty');
    }
    var expectedIndex = 0;
    for (final element in actual) {
      final currentExpected = expected[expectedIndex];
      final matches = currentExpected is Condition<T>
          ? softCheck(element, currentExpected) == null
          : currentExpected is Condition<dynamic>
              ? softCheck(element, currentExpected) == null
              : currentExpected == element;
      if (matches && ++expectedIndex >= expected.length) return null;
    }
    return Rejection(which: [
      ...prefixFirst(
          'did not have an element matching the expectation at index '
          '$expectedIndex ',
          literal(expected[expectedIndex])),
    ]);
  });
}