Skip to content

Commit

Permalink
Merge d474a75 into 71c6388
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesMcIntosh committed Apr 12, 2022
2 parents 71c6388 + d474a75 commit 1e46c08
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/optional.dart
Expand Up @@ -6,5 +6,6 @@ export 'optional_internal.dart'
Optional,
OptionalExtension,
OptionalIterableExtension,
OptionalWrappedIterableExtension,
NoValuePresentError,
empty;
8 changes: 8 additions & 0 deletions lib/src/extension.dart
Expand Up @@ -5,6 +5,14 @@ extension OptionalExtension<T extends Object> on T {
Optional<T> get toOptional => Optional.of(this);
}

extension OptionalWrappedIterableExtension<S, T extends Iterable<S>> on T {
/// Iterable wrapped in Optional, or `Optional.empty()` if the Iterable is empty.
Optional<T> get emptyAsOptional {
if (isEmpty) return Optional.empty();
return Optional.of(this);
}
}

/// Extensions that apply to all iterables.
extension OptionalIterableExtension<T> on Iterable<T> {
/// The first element satisfying [test], or `Optional.empty()` if there are none.
Expand Down
9 changes: 9 additions & 0 deletions test/src/extension.dart
Expand Up @@ -9,6 +9,15 @@ void runExtensionTests() {
expect(1.toOptional, equals(Optional.of(1)));
});
});
group('iterable.emptyAsOptional', () {
test('iterable.emptyAsOptional is present', () {
expect(
<int>[1, 2, 3].emptyAsOptional.value, [1, 2, 3]);
});
test('iterable.emptyAsOptional is empty', () {
expect(<int>[].emptyAsOptional.isEmpty, isTrue);
});
});
group('iterable.firstWhereOptional', () {
test('iterable.firstWhereOptional is present', () {
expect(
Expand Down

0 comments on commit 1e46c08

Please sign in to comment.