Here is a suggestion for you:
import * as A from 'fp-ts/Array'
import {left, right} from 'fp-ts/Either'
import * as R from 'fp-ts/Reader'
import {flow} from 'fp-ts/function'
import type {ReaderEither} from 'fp-ts/ReaderEither'
const sequenceRE: <R, E, A>(
fs: ReaderEither<R, E, A>[]
) => ReaderEither<R, E[], A[]> = flow(
// ReaderEither<<R, E, A>[] -> Reader<R, Either<E, A>[]>
A.sequence(R.reader),
// Maps the reader: Reader<R, Either<E, A>[]> -> ReaderEither<R, E[], A[]>
R.map(flow(
// Either<<E, A>[] -> Separated<E[], A[]>
A.separate,
// Separated<E[], A[]> -> Either<E[], A[]>
s => s.left.length ? left(s.left) : right(s.right)
))
)
// Right [4, 6]
sequenceRE([r => right(r * 2), r => right(r * 3)])(2)
// Left ['foo', 'bar']
sequenceRE([r => right(r * 2), r => left('foo'), r => left('bar')])(2)
// Right []
sequenceRE([])(2)
This code snippet performs the following actions:
sequence
s (from Traversable
) the input array of ReaderEither<R, E, A>
into
Reader<R, Either<E, A>[]>
separate
s (from Compactable
) the Either<E, A>[]
values within the reader, resulting in {left: E[], right: A[]}
interface Separated<A, B> {
readonly left: A
readonly right: B
}
// For Array:
declare const separate: <A, B>(fa: Either<A, B>[]) => Separated<A[], B[]>
If there are any Left
values present, the function will return a Left
with those values. Otherwise, it returns a Right
with the corresponding Right
values.