Skip to content

Commit

Permalink
Add flatMapErr method
Browse files Browse the repository at this point in the history
  • Loading branch information
san-smith committed Jun 1, 2022
1 parent 30b8a99 commit ad2f24b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/src/result.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ abstract class Result<T, E> {
/// Calls `f` if the result is `Ok`, otherwise returns the `Err` value of self.
///
/// This method can be used for control flow based on Result values.
///
/// Example:
/// ```
/// Result<double, String> getReciprocal(double n) => tryCatch(() => 1 / n);
///
Expand All @@ -51,6 +53,14 @@ abstract class Result<T, E> {
(error) => Err(error),
);

/// Calls `f` if the result is `Err`, otherwise returns the `Ok` value of self.
///
/// This method can be used for control flow based on Result values.
Result<T, F> flatMapErr<F>(Result<T, F> Function(E error) f) => fold(
(value) => Ok(value),
(error) => f(error),
);

/// Converts from `Result<T, E>` to `B` by applying a function `ifOk` to a contained `Ok` value and a function `ifErr` to a contained `Err` value.
B fold<B>(B Function(T value) ifOk, B Function(E error) ifErr);

Expand Down
11 changes: 11 additions & 0 deletions test/result_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,17 @@ void main() {
expect(err.flatMap((value) => Ok(value)), err);
});

test('flatMapErr works correctly', () {
final ok = Ok<int, String>(42);
final err = Err<int, String>('error');

expect(ok.flatMapErr((value) => Err(value)), Ok(42));
expect(
err.flatMapErr((value) => Err('Error: $value')),
Err('Error: error'),
);
});

test('mapErr works correctly', () {
final ok = Ok(42);
final err = Err('error');
Expand Down

0 comments on commit ad2f24b

Please sign in to comment.