Skip to content

Commit

Permalink
Merge pull request #22 from faergeek/add-flat-map-err
Browse files Browse the repository at this point in the history
feat: add Result#flatMapErr
  • Loading branch information
faergeek authored Feb 17, 2024
2 parents 7b5f3c5 + da79fee commit e23fb67
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 10 deletions.
45 changes: 35 additions & 10 deletions src/result.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,42 @@ describe('Result', () => {
});

it('#flatMapOk', () => {
const matched = Result.Ok('anything')
.flatMapOk(s =>
s === 'something' ? Result.Ok(s) : Result.Err('Something failed'),
)
.match({
Err: err => err,
Ok: value => value,
});
const matched1 = Result.Ok('anything').flatMapOk(s =>
s === 'anything' ? Result.Ok(42) : Result.Err('No'),
);

expectTypeOf(matched).toEqualTypeOf<string>();
expect(matched).toBe('Something failed');
expectTypeOf(matched1).toEqualTypeOf<Result<number, 'No'>>();
expect(matched1.match({ Err: err => err, Ok: value => value })).toBe(42);

const matched2 = Result.Err('input-error').flatMapOk(value =>
value === 'anything' ? Result.Ok(42) : Result.Err('something'),
);

expectTypeOf(matched2).toEqualTypeOf<
Result<number, 'input-error' | 'something'>
>();

expect(matched2.match({ Err: err => err, Ok: value => value })).toBe(
'input-error',
);
});

it('#flatMapErr', () => {
const matched1 = Result.Err<'input-error' | 'critical-error'>(
'input-error',
).flatMapErr(err =>
err === 'input-error' ? Result.Ok(42) : Result.Err(err),
);

expectTypeOf(matched1).toEqualTypeOf<Result<number, 'critical-error'>>();
expect(matched1.match({ Err: err => err, Ok: value => value })).toBe(42);

const matched2 = Result.Ok('42').flatMapErr(err =>
err === 'input-error' ? Result.Ok(42) : Result.Err('error'),
);

expectTypeOf(matched2).toEqualTypeOf<Result<number | string, 'error'>>();
expect(matched2.match({ Err: err => err, Ok: value => value })).toBe('42');
});

it('#getOk', () => {
Expand Down
15 changes: 15 additions & 0 deletions src/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,21 @@ export class Result<T, E> {
});
}

/**
* Apply an arbitrary transformation to a failure value inside the box and
* return a new box with the result of that transformation.
* As opposed to `mapErr`, `f` is required to return a new box, not just a
* value.
* This can be useful if you want to turn `Result.Err` into `Result.Ok`
* depending on it's value
*/
flatMapErr<U, F>(f: (err: E) => Result<U, F>) {
return this.match<Result<T | U, F>>({
Err: err => f(err),
Ok: Result.Ok,
});
}

/**
* Turn this `Result` into a `Maybe` of a success value.
*/
Expand Down

0 comments on commit e23fb67

Please sign in to comment.