Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(655)

Unified Diff: lib/src/transformers/scan.dart

Issue 1648963002: Add reactive-inspired stream transformers: Base URL: https://github.com/dart-lang/async@master
Patch Set: Restructure failes and add more tests. Created 4 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: lib/src/transformers/scan.dart
diff --git a/lib/src/transformers/scan.dart b/lib/src/transformers/scan.dart
new file mode 100644
index 0000000000000000000000000000000000000000..4b823a2b25907e4c3fbbcdba9a0865022473c8c3
--- /dev/null
+++ b/lib/src/transformers/scan.dart
@@ -0,0 +1,39 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import "dart:async";
+
+/// Updates an accumulator with each event and emits the intermediate results.
+///
+/// Combines each event with the previous accumulator value
+/// and emits the new result.
+///
+/// Example:
+/// ```dart
+/// var stream = new Stream.fromIterable([1, 2, 3, 4, 5]);
+/// var result = await stream.transform(new Scan(1, (a, b) => a * b)).toList();
+/// print(result); // [1, 2, 6, 24, 120]
+/// ```
+///
+/// The last result emitted by `stream.transform(new Scan(a, c))`
+/// is the same result that would be computed by `stream.fold(a, c)`.
+///
+/// Errors in the source stream or from calling the combine function
+/// are reported on the result stream and abort the transformation.
+class Scan<S, A> implements StreamTransformer<S, A> {
floitsch 2016/02/26 13:50:44 I'm still not convinced that "Scan" is a good name
nweiz 2016/03/01 02:10:04 I think matching Reactive here is worth the odd na
+ final A _initial;
+ final Function _combine;
+
+ /// Accumulates stream events using [combine] starting with [initial].
+ Scan(A initial, A combine(A accumulator, S source))
+ : _initial = initial, _combine = combine;
+
+ Stream<A> bind(Stream<S> stream) async* {
+ A accumulator = _initial;
+ await for (S source in stream) {
+ accumulator = _combine(accumulator, source);
+ yield accumulator;
+ }
+ }
+}

Powered by Google App Engine
This is Rietveld 408576698