Skip to content

Commit

Permalink
Adding toErrorIf method (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucastsantos committed Oct 29, 2023
1 parent fd4c004 commit 3443157
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

- Breaking change: Raised minimum Dart to >=3.0.0
- Added `partition`, `getAll` and `getAllErrors` for interacting with a list of results
- Added `toErrorIf` method

## 1.0.2

Expand Down
18 changes: 18 additions & 0 deletions lib/src/functions/map.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,22 @@ extension MapResult<T, E> on Result<T, E> {
return Err<F>(failure((result as Err<E>).error));
}
}

/// Transforms a success into an error if it satisfies the given [predicate],
/// otherwise return this Result.
Result<T, E> toErrorIf(
bool Function(T value) predicate,
E Function(T value) transform,
) {
final result = this;
if (result is Ok<T>) {
if (predicate(result.value)) {
return Err(transform(result.value));
} else {
return result;
}
} else {
return result;
}
}
}
19 changes: 19 additions & 0 deletions test/functions/map_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,25 @@ void main() {
});
});

group('toErrorIf', () {
test('should not transform success if does not satisfies the condition',
() {
final Result<int, String> result = const Ok(1);
expect(result.toErrorIf((_) => false, (_) => "error"), const Ok(1));
});

test('should transform success if satisfies the condition', () {
final Result<int, String> result = const Ok(1);
expect(result.toErrorIf((_) => true, (_) => "error"), const Err("error"));
});

test('should not transform failures', () {
final Result<int, String> result = const Err("original");
expect(result.toErrorIf((_) => true, (_) => "modified"),
const Err("original"));
});
});

test('Map extension name should not conflict with Dart Map', () {
Result<Map<String, String>, Never> result = const Ok(0).map((value) => {});
expect(result, isA<Ok<Map<String, String>>>());
Expand Down

0 comments on commit 3443157

Please sign in to comment.