Skip to content

Commit

Permalink
Add also scope operator.
Browse files Browse the repository at this point in the history
  • Loading branch information
renggli committed Dec 14, 2023
1 parent 006838b commit d8bb634
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/functional.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ library functional;

export 'src/functional/either.dart' show Either;
export 'src/functional/optional.dart' show Optional;
export 'src/functional/scope.dart' show ScopeFunctionExtension;
export 'src/functional/types.dart';
18 changes: 18 additions & 0 deletions lib/src/functional/scope.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
extension ScopeFunctionExtension<T> on T {
/// Evaluates the [callback] with the receiver as the argument and returns
/// its return value.
///
/// In a cascade, this is useful to chain calls to other functions:
///
/// [1, 2, 3]
/// ..also((list) => print('Before: $list'))
/// ..add(4)
/// ..also((list) => print('After: $list'));
///
/// On a nullable value, this is useful to only evaluate code on non-null
/// objects:
///
/// nullableObject?.also((nonNull) => print('Not null: $nonNull'));
///
S also<S>(S Function(T value) callback) => callback(this);
}
21 changes: 21 additions & 0 deletions test/functional_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -401,4 +401,25 @@ void main() {
});
});
});
group('scope', () {
test('also 1', () {
final results = <String>[];
[1, 2, 3]
..also((list) => results.add('Before: $list'))
..add(4)
..also((list) => results.add('After: $list'));
expect(results, ['Before: [1, 2, 3]', 'After: [1, 2, 3, 4]']);
});
test('also 2', () {
final results = <String>[];
for (final value in <int?>[null, 42]) {
final result = value?.also((value) {
results.add('Value: $value');
return value;
});
expect(result, value);
}
expect(results, ['Value: 42']);
});
});
}

0 comments on commit d8bb634

Please sign in to comment.