traverseListWithIndex<A, B> static method

Option<List<B>> traverseListWithIndex<A, B>(
  1. List<A> list,
  2. Option<B> f(
    1. A a,
    2. int i
    )
)

Map each element in the list to an Option using the function f, and collect the result in an Option<List<B>>.

If any mapped element of the list is None, then the final result will be None.

Same as Option.traverseList but passing index in the map function.

Implementation

static Option<List<B>> traverseListWithIndex<A, B>(
  List<A> list,
  Option<B> Function(A a, int i) f,
) {
  final resultList = <B>[];
  for (var i = 0; i < list.length; i++) {
    final o = f(list[i], i);
    final r = o.match<B?>(() => null, identity);
    if (r == null) return none();
    resultList.add(r);
  }

  return some(resultList);
}