sequence<L, R> static method

  1. @useResult
Either<L, BuiltList<R>> sequence<L, R>(
  1. Iterable<Either<L, R>> values
)

Sequences all Either values. If one of them is a Left, then it will short-circuit the operation, and returning the first encountered Left.

Otherwise, collects all values and wrap them in a Right.

Example

// Result: Left('3')
Either.sequence<int, String>([1, 2, 3, 4, 5, 6]
    .map((int i) => i < 3 ? i.toString().right() : i.left()));

// Result: Right(BuiltList.of(['1', '2', '3', '4', '5', '6']))
Either.sequence<int, String>(
    [1, 2, 3, 4, 5, 6].map((int i) => i.toString().right()));

Implementation

@useResult
static Either<L, BuiltList<R>> sequence<L, R>(Iterable<Either<L, R>> values) {
  final result = ListBuilder<R>();

  for (final either in values) {
    switch (either) {
      case Left(value: final l):
        return Either<L, BuiltList<R>>.left(l);
      case Right(value: final r):
        result.add(r);
    }
  }

  return Right(result.build());
}