Open History to see the last commit
1import { DifferenceStreamWriter, LinearUnaryOperator } from '../graph.js'
2import { StreamBuilder } from '../d2.js'
3import type { IStreamBuilder, PipedOperator } from '../types.js'
4import type { DifferenceStreamReader } from '../graph.js'
5import type { MultiSet } from '../multiset.js'
6
7/**
8 * Operator that applies a function to each multi-set in the input stream
9 */
10export class TapOperator<T> extends LinearUnaryOperator<T, T> {
11 #f: (data: MultiSet<T>) => void
12
13 constructor(
14 id: number,
15 inputA: DifferenceStreamReader<T>,
16 output: DifferenceStreamWriter<T>,
17 f: (data: MultiSet<T>) => void,
18 ) {
19 super(id, inputA, output)
20 this.#f = f
21 }
22
23 inner(collection: MultiSet<T>): MultiSet<T> {
24 this.#f(collection)
25 return collection
26 }
27}
28
29/**
30 * Invokes a function for each multi-set in the input stream.
31 * This operator doesn't modify the stream and is used to perform side effects.
32 * @param f - The function to invoke on each multi-set
33 * @returns The input stream
34 */
35export function tap<T>(f: (data: MultiSet<T>) => void): PipedOperator<T, T> {
36 return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {
37 const output = new StreamBuilder<T>(
38 stream.graph,
39 new DifferenceStreamWriter<T>(),
40 )
41 const operator = new TapOperator<T>(
42 stream.graph.getNextOperatorId(),
43 stream.connectReader(),
44 output.writer,
45 f,
46 )
47 stream.graph.addOperator(operator)
48 return output
49 }
50}