purify
purify copied to clipboard
chainNullable for Either
Sometimes when I'm mapping over an Either that contains an object or an array, I want to do a similar action as chainNullable from the Maybe type does.
type MyType = { [key: string]: number }
const a: MyType = { a: 1 };
const either: Either<string, MyType> = Right(a);
const eitherNumber = either.chainNullable(obj => obj['a'], 'Left in case of not found');
Current workaround is:
type MyType = { [key: string]: number }
const a: MyType = { a: 1 };
const either: Either<string, MyType> = Right(a);
const eitherNumber = either.chain(obj => {
return Maybe.fromNullable(
obj['a'],
).toEither('Left in case of not found');
});
I was wondering if this usecase was usefull enough to warrant a helper method on the Either type.