singleWhereIndexedOptional method

Optional<T> singleWhereIndexedOptional(
  1. bool test(
    1. int index,
    2. T element
    )
)

The single element satisfying test.

Returns Optional.empty() if there are either none or more than one element and index satisfying test.

Implementation

Optional<T> singleWhereIndexedOptional(
    bool Function(int index, T element) test) {
  T? result;
  var found = false;
  var index = 0;
  for (var element in this) {
    if (test(index++, element)) {
      if (!found) {
        result = element;
        found = true;
      } else {
        return Optional.empty();
      }
    }
  }
  return Optional.ofNullable(result);
}