containsMatchingInOrder method

void containsMatchingInOrder(
  1. Iterable<Condition<T>> conditions
)

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

For example, the following will succeed:

check([1, 10, 2, 10, 3]).containsMatchingInOrder([
  .it()..isLessThan(2),
  .it()..isLessThan(3),
  .it()..isLessThan(4),
]);
import 'package:checks/checks.dart';
import 'package:test/scaffolding.dart';

void main() {
  test('containsMatchingInOrder', () {
    // This check succeeds.
    check([1, 10, 2, 10, 3]).containsMatchingInOrder([
      .it()..isLessThan(2),
      .it()..isLessThan(3),
      .it()..isLessThan(4),
    ]);

    // This check fails.
    check([
      1,
      10,
      2,
      10,
      3,
    ]).containsMatchingInOrder([.it()..isLessThan(2), .it()..isLessThan(0)]);
    // Expected: a List<int> that:
    //   contains, in order: [<A value that:
    //     is less than <2>>,
    //   <A value that:
    //     is less than <0>>]
    // Actual: [1, 10, 2, 10, 3]
    // Which: did not have an element matching the expectation at index 1 <A value that:
    //   is less than <0>>
  });
}

Implementation

void containsMatchingInOrder(Iterable<Condition<T>> conditions) {
  context.expect(
    () => prefixFirst('contains, in order: ', literal(conditions)),
    (actual) {
      final expected = conditions.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.softCheckSync(element) == null;
        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]),
          ),
        ],
      );
    },
  );
}