Open History to see the last commit
1import { DifferenceStreamWriter, UnaryOperator } from "../graph.js"
2import { StreamBuilder } from "../d2.js"
3import { MultiSet } from "../multiset.js"
4import type { IStreamBuilder, PipedOperator } from "../types.js"
5
6/**
7 * Operator that consolidates collections
8 */
9export class ConsolidateOperator<T> extends UnaryOperator<T> {
10 run(): void {
11 const messages = this.inputMessages()
12 if (messages.length === 0) {
13 return
14 }
15
16 // Combine all messages into a single MultiSet
17 const combined = new MultiSet<T>()
18 for (const message of messages) {
19 combined.extend(message)
20 }
21
22 // Consolidate the combined MultiSet
23 const consolidated = combined.consolidate()
24
25 // Only send if there are results
26 if (consolidated.getInner().length > 0) {
27 this.output.sendData(consolidated)
28 }
29 }
30}
31
32/**
33 * Consolidates the elements in the stream
34 */
35export function consolidate<T>(): PipedOperator<T, T> {
36 return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {
37 const output = new StreamBuilder<T>(
38 stream.graph,
39 new DifferenceStreamWriter<T>()
40 )
41 const operator = new ConsolidateOperator<T>(
42 stream.graph.getNextOperatorId(),
43 stream.connectReader(),
44 output.writer
45 )
46 stream.graph.addOperator(operator)
47 stream.graph.addStream(output.connectReader())
48 return output
49 }
50}