From d8bb634f7765c2096b4b09bbdbf0537be413c057 Mon Sep 17 00:00:00 2001 From: Lukas Renggli Date: Thu, 14 Dec 2023 09:39:50 +0100 Subject: [PATCH] Add `also` scope operator. --- lib/functional.dart | 1 + lib/src/functional/scope.dart | 18 ++++++++++++++++++ test/functional_test.dart | 21 +++++++++++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 lib/src/functional/scope.dart diff --git a/lib/functional.dart b/lib/functional.dart index 5c01941..65f719e 100644 --- a/lib/functional.dart +++ b/lib/functional.dart @@ -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'; diff --git a/lib/src/functional/scope.dart b/lib/src/functional/scope.dart new file mode 100644 index 0000000..c5f49c4 --- /dev/null +++ b/lib/src/functional/scope.dart @@ -0,0 +1,18 @@ +extension ScopeFunctionExtension 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 Function(T value) callback) => callback(this); +} diff --git a/test/functional_test.dart b/test/functional_test.dart index 62dc138..f8fd6e9 100644 --- a/test/functional_test.dart +++ b/test/functional_test.dart @@ -401,4 +401,25 @@ void main() { }); }); }); + group('scope', () { + test('also 1', () { + final results = []; + [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 = []; + for (final value in [null, 42]) { + final result = value?.also((value) { + results.add('Value: $value'); + return value; + }); + expect(result, value); + } + expect(results, ['Value: 42']); + }); + }); }