traverseListWithIndex<E, A, B> static method

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

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

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

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

Implementation

static Either<E, List<B>> traverseListWithIndex<E, A, B>(
  List<A> list,
  Either<E, B> Function(A a, int i) f,
) {
  final resultList = <B>[];
  for (var i = 0; i < list.length; i++) {
    final e = f(list[i], i);
    if (e is Left<E, B>) {
      return left(e._value);
    } else if (e is Right<E, B>) {
      resultList.add(e._value);
    } else {
      throw Exception(
        "[fpdart]: Error when mapping Either, it should be either Left or Right.",
      );
    }
  }

  return right(resultList);
}