@@ -73,6 +73,19 @@ class FlowOps[+T]:
73
73
def filter (f : T => Boolean ): Flow [T ] = Flow .usingEmitInline: emit =>
74
74
last.run(FlowEmit .fromInline(t => if f(t) then emit.apply(t)))
75
75
76
+ /** Emits only every nth element emitted by this flow.
77
+ *
78
+ * @param n
79
+ * The interval between two emitted elements.
80
+ */
81
+ def sample (n : Int ): Flow [T ] = Flow .usingEmitInline: emit =>
82
+ var sampleCounter = 0
83
+ last.run(
84
+ FlowEmit .fromInline: t =>
85
+ sampleCounter += 1
86
+ if n != 0 && sampleCounter % n == 0 then emit(t)
87
+ )
88
+
76
89
/** Applies the given mapping function `f` to each element emitted by this flow, for which the function is defined, and emits the result.
77
90
* If `f` is not defined at an element, the element will be skipped.
78
91
*
@@ -82,6 +95,23 @@ class FlowOps[+T]:
82
95
def collect [U ](f : PartialFunction [T , U ]): Flow [U ] = Flow .usingEmitInline: emit =>
83
96
last.run(FlowEmit .fromInline(t => if f.isDefinedAt(t) then emit.apply(f(t))))
84
97
98
+ /** Transforms the elements of the flow by applying an accumulation function to each element, producing a new value at each step. The
99
+ * resulting flow contains the accumulated values at each point in the original flow.
100
+ *
101
+ * @param initial
102
+ * The initial value to start the accumulation.
103
+ * @param f
104
+ * The accumulation function that is applied to each element of the flow.
105
+ */
106
+ def scan [V ](initial : V )(f : (V , T ) => V ): Flow [V ] = Flow .usingEmitInline: emit =>
107
+ emit(initial)
108
+ var accumulator = initial
109
+ last.run(
110
+ FlowEmit .fromInline: t =>
111
+ accumulator = f(accumulator, t)
112
+ emit(accumulator)
113
+ )
114
+
85
115
/** Applies the given effectful function `f` to each element emitted by this flow. The returned flow emits the elements unchanged. If `f`
86
116
* throws an exceptions, the flow fails and propagates the exception.
87
117
*/
@@ -441,6 +471,17 @@ class FlowOps[+T]:
441
471
emit((t, otherDefault)); true
442
472
)
443
473
474
+ /** Combines each element from this and the index of the element (starting at 0).
475
+ */
476
+ def zipWithIndex : Flow [(T , Long )] = Flow .usingEmitInline: emit =>
477
+ var index = 0L
478
+ last.run(
479
+ FlowEmit .fromInline: t =>
480
+ val zipped = (t, index)
481
+ index += 1
482
+ emit(zipped)
483
+ )
484
+
444
485
/** Emits a given number of elements (determined byc `segmentSize`) from this flow to the returned flow, then emits the same number of
445
486
* elements from the `other` flow and repeats. The order of elements in both flows is preserved.
446
487
*
0 commit comments