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

map.ts

37 lines968 Bytes

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 element in the input stream
12 */
13export class MapOperator<T, U> extends LinearUnaryOperator<T, U> {
14 #f: (data: T) => U
15​
16 constructor(
17 id: number,
18 inputA: DifferenceStreamReader<T>,
19 output: DifferenceStreamWriter<U>,
20 f: (data: T) => U,
21 ) {
22 super(id, inputA, output)
23 this.#f = f
24 }
25​
26 inner(collection: MultiSet<T>): MultiSet<U> {
27 return collection.map(this.#f)
28 }
30​
31/**
32 * Applies a function to each element in the input stream
33 * @param f - The function to apply to each element
34 */
35export function map<T, O>(f: (data: T) => O): PipedOperator<T, O> {
36 return unaryOperator(MapOperator<T, O>, f)