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

reduce.ts

139 lines4.6 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: 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 options?: ReduceOptions,
22 ) {
23 super(id, inputA, output)
24 this.#index = new Index<K, V1>(options)
25 this.#f = f
26 }
27​
28 run(): void {
29 // Collect all input messages and update the index
30 const keysTodo = new Set<K>()
31 for (const message of this.inputMessages()) {
32 for (const [item, multiplicity] of message.getInner()) {
33 const [key, value] = item
34 this.#index.addValue(key, [value, multiplicity])
35 keysTodo.add(key)
36 }
37 }
38​
39 // For each key, compute the reduction and delta
40 const result: Array<[[K, V2], number]> = []
41 for (const key of keysTodo) {
42 const curr = this.#index.get(key)
43 const currOut = this.#indexOut.get(key)
44 const out = this.#f(curr)
45​
46 // Create maps for current and previous outputs using values directly as keys
47 const newOutputMap = new Map<V2, number>()
48 const oldOutputMap = new Map<V2, number>()
49​
50 // Process new output
51 for (const [value, multiplicity] of out) {
52 const existing = newOutputMap.get(value) ?? 0
53 newOutputMap.set(value, existing + multiplicity)
54 }
55​
56 // Process previous output
57 for (const [value, multiplicity] of currOut) {
58 const existing = oldOutputMap.get(value) ?? 0
59 oldOutputMap.set(value, existing + multiplicity)
60 }
61​
62 // First, emit removals for old values that are no longer present
63 for (const [value, multiplicity] of oldOutputMap) {
64 if (!newOutputMap.has(value)) {
65 // Remove the old value entirely
66 result.push([[key, value], -multiplicity])
67 this.#indexOut.addValue(key, [value, -multiplicity])
68 }
69 }
70​
71 // Then, emit additions for new values that are not present in old
72 for (const [value, multiplicity] of newOutputMap) {
73 if (!oldOutputMap.has(value)) {
74 // Add the new value only if it has non-zero multiplicity
75 if (multiplicity !== 0) {
76 result.push([[key, value], multiplicity])
77 this.#indexOut.addValue(key, [value, multiplicity])
78 }
79 }
80 }
81​
82 // Finally, emit multiplicity changes for values that were present and are still present
83 for (const [value, newMultiplicity] of newOutputMap) {
84 const oldMultiplicity = oldOutputMap.get(value)
85 if (oldMultiplicity !== undefined) {
86 const delta = newMultiplicity - oldMultiplicity
87 // Only emit actual changes, i.e. non-zero deltas
88 if (delta !== 0) {
89 result.push([[key, value], delta])
90 this.#indexOut.addValue(key, [value, delta])
91 }
92 }
93 }
94 }
95​
96 if (result.length > 0) {
97 this.output.sendData(new MultiSet(result))
98 }
99 }
101​
102/** @internal groupBy's option; its producer must keep the identity exact. */
103export type ReduceOptions = {
104 /**
105 * Input values are `[identity, value]` with a string or number identity
106 * that determines the value: two inputs under one key with an equal
107 * identity are equal. They merge without a structural hash.
108 */
109 prefixIdentity?: boolean
111​
112/**
113 * Reduces the elements in the stream by key (version-free)
114 */
115export function reduce<
116 KType extends (T extends KeyValue<infer K, infer _V> ? K : never),
117 V1Type extends (T extends KeyValue<KType, infer V> ? V : never),
118 R,
119 T,
120>(
121 f: (values: Array<[V1Type, number]>) => Array<[R, number]>,
122 options?: ReduceOptions,
123) {
124 return (stream: IStreamBuilder<T>): IStreamBuilder<KeyValue<KType, R>> => {
125 const output = new StreamBuilder<KeyValue<KType, R>>(
126 stream.graph,
127 new DifferenceStreamWriter<KeyValue<KType, R>>(),
128 )
129 const operator = new ReduceOperator<KType, V1Type, R>(
130 stream.graph.getNextOperatorId(),
131 stream.connectReader() as DifferenceStreamReader<KeyValue<KType, V1Type>>,
132 output.writer,
133 f,
134 options,
135 )
136 stream.graph.addOperator(operator)
137 return output
138 }