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

tap.ts

40 lines1.1 KB

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