purify icon indicating copy to clipboard operation
purify copied to clipboard

chainNullable for Either

Open mahulst opened this issue 2 years ago • 0 comments

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.

mahulst avatar Jul 19 '22 11:07 mahulst