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

map.ts

47 lines1.3 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 MapOperator<T, U> extends LinearUnaryOperator<T, U> {
11 #f: (data: T) => U
12​
13 constructor(
14 id: number,
15 inputA: DifferenceStreamReader<T>,
16 output: DifferenceStreamWriter<U>,
17 f: (data: T) => U
18 ) {
19 super(id, inputA, output)
20 this.#f = f
21 }
22​
23 inner(collection: MultiSet<T>): MultiSet<U> {
24 return collection.map(this.#f)
25 }
27​
28/**
29 * Applies a function to each element in the input stream
30 * @param f - The function to apply to each element
31 */
32export function map<T, O>(f: (data: T) => O): PipedOperator<T, O> {
33 return (stream: IStreamBuilder<T>): IStreamBuilder<O> => {
34 const output = new StreamBuilder<O>(
35 stream.graph,
36 new DifferenceStreamWriter<O>()
37 )
38 const operator = new MapOperator<T, O>(
39 stream.graph.getNextOperatorId(),
40 stream.connectReader(),
41 output.writer,
42 f
43 )
44 stream.graph.addOperator(operator)
45 return output
46 }