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

reduce.ts

180 lines6.1 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/** The key identity of a Map: SameValueZero, so NaN equals NaN. */
9function sameOutput(left: unknown, right: unknown): boolean {
10 return left === right || (left !== left && right !== right)
12​
13/** The value a Map stores as a key: -0 becomes 0. */
14function asMapKey<T>(value: T): T {
15 return (value === 0 ? 0 : value) as T
17​
18/**
19 * Base operator for reduction operations (version-free)
20 */
21export class ReduceOperator<K, V1, V2> extends UnaryOperator<[K, V1], [K, V2]> {
22 // Reduce never reads presence, so its indexes skip that bookkeeping.
23 #index: Index<K, V1>
24 #indexOut = new Index<K, V2>({ trackPresence: false })
25 #f: (values: Array<[V1, number]>) => Array<[V2, number]>
26​
27 constructor(
28 id: number,
29 inputA: DifferenceStreamReader<[K, V1]>,
30 output: DifferenceStreamWriter<[K, V2]>,
31 f: (values: Array<[V1, number]>) => Array<[V2, number]>,
32 options?: ReduceOptions,
33 ) {
34 super(id, inputA, output)
35 this.#index = new Index<K, V1>({ ...options, trackPresence: false })
36 this.#f = f
37 }
38​
39 run(): void {
40 // Collect all input messages and update the index
41 const keysTodo = new Set<K>()
42 for (const message of this.inputMessages()) {
43 for (const [item, multiplicity] of message.getInner()) {
44 const [key, value] = item
45 this.#index.addValue(key, [value, multiplicity])
46 keysTodo.add(key)
47 }
48 }
49​
50 // For each key, compute the reduction and delta
51 const result: Array<[[K, V2], number]> = []
52 for (const key of keysTodo) {
53 const curr = this.#index.get(key)
54 const currOut = this.#indexOut.get(key)
55 const out = this.#f(curr)
56​
57 // Most keys have at most one output before and after. Compare the two
58 // directly, by the SameValueZero identity the maps below use.
59 if (out.length <= 1 && currOut.length <= 1) {
60 // Earlier outputs were stored as Map keys, so only the new one needs it.
61 const before = currOut[0]
62 const after = out[0]
63 const value = after === undefined ? undefined : asMapKey(after[0])
64 if (
65 before !== undefined &&
66 after !== undefined &&
67 sameOutput(before[0], value)
68 ) {
69 const delta = after[1] - before[1]
70 if (delta !== 0) {
71 result.push([[key, before[0]], delta])
72 this.#indexOut.addValue(key, [before[0], delta])
73 }
74 continue
75 }
76 if (before !== undefined) {
77 result.push([[key, before[0]], -before[1]])
78 this.#indexOut.addValue(key, [before[0], -before[1]])
79 }
80 if (after !== undefined && after[1] !== 0) {
81 result.push([[key, value as V2], after[1]])
82 this.#indexOut.addValue(key, [value as V2, after[1]])
83 }
84 continue
85 }
86​
87 // Create maps for current and previous outputs using values directly as keys
88 const newOutputMap = new Map<V2, number>()
89 const oldOutputMap = new Map<V2, number>()
90​
91 // Process new output
92 for (const [value, multiplicity] of out) {
93 const existing = newOutputMap.get(value) ?? 0
94 newOutputMap.set(value, existing + multiplicity)
95 }
96​
97 // Process previous output
98 for (const [value, multiplicity] of currOut) {
99 const existing = oldOutputMap.get(value) ?? 0
100 oldOutputMap.set(value, existing + multiplicity)
101 }
102​
103 // First, emit removals for old values that are no longer present
104 for (const [value, multiplicity] of oldOutputMap) {
105 if (!newOutputMap.has(value)) {
106 // Remove the old value entirely
107 result.push([[key, value], -multiplicity])
108 this.#indexOut.addValue(key, [value, -multiplicity])
109 }
110 }
111​
112 // Then, emit additions for new values that are not present in old
113 for (const [value, multiplicity] of newOutputMap) {
114 if (!oldOutputMap.has(value)) {
115 // Add the new value only if it has non-zero multiplicity
116 if (multiplicity !== 0) {
117 result.push([[key, value], multiplicity])
118 this.#indexOut.addValue(key, [value, multiplicity])
119 }
120 }
121 }
122​
123 // Finally, emit multiplicity changes for values that were present and are still present
124 for (const [value, newMultiplicity] of newOutputMap) {
125 const oldMultiplicity = oldOutputMap.get(value)
126 if (oldMultiplicity !== undefined) {
127 const delta = newMultiplicity - oldMultiplicity
128 // Only emit actual changes, i.e. non-zero deltas
129 if (delta !== 0) {
130 result.push([[key, value], delta])
131 this.#indexOut.addValue(key, [value, delta])
132 }
133 }
134 }
135 }
136​
137 if (result.length > 0) {
138 this.output.sendData(new MultiSet(result))
139 }
140 }
142​
143/** @internal groupBy's option; its producer must keep the identity exact. */
144export type ReduceOptions = {
145 /**
146 * Input values are `[identity, value]` with a string or number identity
147 * that determines the value: two inputs under one key with an equal
148 * identity are equal. They merge without a structural hash.
149 */
150 prefixIdentity?: boolean
152​
153/**
154 * Reduces the elements in the stream by key (version-free)
155 */
156export function reduce<
157 KType extends (T extends KeyValue<infer K, infer _V> ? K : never),
158 V1Type extends (T extends KeyValue<KType, infer V> ? V : never),
159 R,
160 T,
161>(
162 f: (values: Array<[V1Type, number]>) => Array<[R, number]>,
163 options?: ReduceOptions,
164) {
165 return (stream: IStreamBuilder<T>): IStreamBuilder<KeyValue<KType, R>> => {
166 const output = new StreamBuilder<KeyValue<KType, R>>(
167 stream.graph,
168 new DifferenceStreamWriter<KeyValue<KType, R>>(),
169 )
170 const operator = new ReduceOperator<KType, V1Type, R>(
171 stream.graph.getNextOperatorId(),
172 stream.connectReader() as DifferenceStreamReader<KeyValue<KType, V1Type>>,
173 output.writer,
174 f,
175 options,
176 )
177 stream.graph.addOperator(operator)
178 return output
179 }