Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

tap.ts

53 lines1.5 KB

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 element in the input stream
9 */
10export class TapOperator<T> extends LinearUnaryOperator<T, T> {
11 #f: (data: T) => void
12​
13 constructor(
14 id: number,
15 inputA: DifferenceStreamReader<T>,
16 output: DifferenceStreamWriter<T>,
17 f: (data: T) => void
18 ) {
19 super(id, inputA, output)
20 this.#f = f
21 }
22​
23 inner(collection: MultiSet<T>): MultiSet<T> {
24 return collection.map((data) => {
25 this.#f(data)
26 return data
27 })
28 }
30​
31/**
32 * Invokes a function for each element in the input stream.
33 * This operator doesn't modify the stream and is used to perform side effects.
34 * @param f - The function to invoke on each element
35 * @returns The input stream
36 */
37export function tap<T>(f: (data: T) => void): PipedOperator<T, T> {
38 return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {
39 const output = new StreamBuilder<T>(
40 stream.graph,
41 new DifferenceStreamWriter<T>()
42 )
43 const operator = new TapOperator<T>(
44 stream.graph.getNextOperatorId(),
45 stream.connectReader(),
46 output.writer,
47 f
48 )
49 stream.graph.addOperator(operator)
50 stream.graph.addStream(output.connectReader())
51 return output
52 }