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