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

reduce.ts

124 lines4.2 KB

1import { DifferenceStreamWriter, UnaryOperator } from "../graph.js"
2import { StreamBuilder } from "../d2.js"
3import { MultiSet } from "../multiset.js"
4import { Index } from "../indexes.js"
5import type { DifferenceStreamReader } from "../graph.js"
6import type { IStreamBuilder, KeyValue } from "../types.js"
7​
8/**
9 * Base operator for reduction operations (version-free)
10 */
11export class ReduceOperator<K, V1, V2> extends UnaryOperator<[K, V1], [K, V2]> {
12 #index = new Index<K, V1>()
13 #indexOut = new Index<K, V2>()
14 #f: (values: Array<[V1, number]>) => Array<[V2, number]>
15​
16 constructor(
17 id: number,
18 inputA: DifferenceStreamReader<[K, V1]>,
19 output: DifferenceStreamWriter<[K, V2]>,
20 f: (values: Array<[V1, number]>) => Array<[V2, number]>
21 ) {
22 super(id, inputA, output)
23 this.#f = f
24 }
25​
26 run(): void {
27 // Collect all input messages and update the index
28 const keysTodo = new Set<K>()
29 for (const message of this.inputMessages()) {
30 for (const [item, multiplicity] of message.getInner()) {
31 const [key, value] = item
32 this.#index.addValue(key, [value, multiplicity])
33 keysTodo.add(key)
34 }
35 }
36​
37 // For each key, compute the reduction and delta
38 const result: Array<[[K, V2], number]> = []
39 for (const key of keysTodo) {
40 const curr = this.#index.get(key)
41 const currOut = this.#indexOut.get(key)
42 const out = this.#f(curr)
43​
44 // Create maps for current and previous outputs using values directly as keys
45 const newOutputMap = new Map<V2, number>()
46 const oldOutputMap = new Map<V2, number>()
47​
48 // Process new output
49 for (const [value, multiplicity] of out) {
50 const existing = newOutputMap.get(value) ?? 0
51 newOutputMap.set(value, existing + multiplicity)
52 }
53​
54 // Process previous output
55 for (const [value, multiplicity] of currOut) {
56 const existing = oldOutputMap.get(value) ?? 0
57 oldOutputMap.set(value, existing + multiplicity)
58 }
59​
60 // First, emit removals for old values that are no longer present
61 for (const [value, multiplicity] of oldOutputMap) {
62 if (!newOutputMap.has(value)) {
63 // Remove the old value entirely
64 result.push([[key, value], -multiplicity])
65 this.#indexOut.addValue(key, [value, -multiplicity])
66 }
67 }
68​
69 // Then, emit additions for new values that are not present in old
70 for (const [value, multiplicity] of newOutputMap) {
71 if (!oldOutputMap.has(value)) {
72 // Add the new value only if it has non-zero multiplicity
73 if (multiplicity !== 0) {
74 result.push([[key, value], multiplicity])
75 this.#indexOut.addValue(key, [value, multiplicity])
76 }
77 }
78 }
79​
80 // Finally, emit multiplicity changes for values that were present and are still present
81 for (const [value, newMultiplicity] of newOutputMap) {
82 const oldMultiplicity = oldOutputMap.get(value)
83 if (oldMultiplicity !== undefined) {
84 const delta = newMultiplicity - oldMultiplicity
85 // Only emit actual changes, i.e. non-zero deltas
86 if (delta !== 0) {
87 result.push([[key, value], delta])
88 this.#indexOut.addValue(key, [value, delta])
89 }
90 }
91 }
92 }
93​
94 if (result.length > 0) {
95 this.output.sendData(new MultiSet(result))
96 }
97 }
99​
100/**
101 * Reduces the elements in the stream by key (version-free)
102 */
103export function reduce<
104 KType extends T extends KeyValue<infer K, infer _V> ? K : never,
105 V1Type extends T extends KeyValue<KType, infer V> ? V : never,
106 R,
107 T,
108>(f: (values: Array<[V1Type, number]>) => Array<[R, number]>) {
109 return (stream: IStreamBuilder<T>): IStreamBuilder<KeyValue<KType, R>> => {
110 const output = new StreamBuilder<KeyValue<KType, R>>(
111 stream.graph,
112 new DifferenceStreamWriter<KeyValue<KType, R>>()
113 )
114 const operator = new ReduceOperator<KType, V1Type, R>(
115 stream.graph.getNextOperatorId(),
116 stream.connectReader() as DifferenceStreamReader<KeyValue<KType, V1Type>>,
117 output.writer,
118 f
119 )
120 stream.graph.addOperator(operator)
121 stream.graph.addStream(output.connectReader())
122 return output
123 }