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

distinct.ts

98 lines2.8 KB

1import { DifferenceStreamWriter, UnaryOperator } from "../graph.js"
2import { StreamBuilder } from "../d2.js"
3import { hash } from "../utils.js"
4import { MultiSet } from "../multiset.js"
5import type { DifferenceStreamReader } from "../graph.js"
6import type { IStreamBuilder } from "../types.js"
7​
8type HashedValue = string
9type Multiplicity = number
10​
11/**
12 * Operator that removes duplicates
13 */
14export class DistinctOperator<T> extends UnaryOperator<T> {
15 #by: (value: T) => any
16 #values: Map<HashedValue, Multiplicity> // keeps track of the number of times each value has been seen
17​
18 constructor(
19 id: number,
20 input: DifferenceStreamReader<T>,
21 output: DifferenceStreamWriter<T>,
22 by: (value: T) => any = (value: T) => value
23 ) {
24 super(id, input, output)
25 this.#by = by
26 this.#values = new Map()
27 }
28​
29 run(): void {
30 const updatedValues = new Map<HashedValue, [Multiplicity, T]>()
31​
32 // Compute the new multiplicity for each value
33 for (const message of this.inputMessages()) {
34 for (const [value, diff] of message.getInner()) {
35 const hashedValue = hash(this.#by(value))
36​
37 const oldMultiplicity =
38 updatedValues.get(hashedValue)?.[0] ??
39 this.#values.get(hashedValue) ??
40 0
41 const newMultiplicity = oldMultiplicity + diff
42​
43 updatedValues.set(hashedValue, [newMultiplicity, value])
44 }
45 }
46​
47 const result: Array<[T, number]> = []
48​
49 // Check which values became visible or disappeared
50 for (const [
51 hashedValue,
52 [newMultiplicity, value],
53 ] of updatedValues.entries()) {
54 const oldMultiplicity = this.#values.get(hashedValue) ?? 0
55​
56 if (newMultiplicity === 0) {
57 this.#values.delete(hashedValue)
58 } else {
59 this.#values.set(hashedValue, newMultiplicity)
60 }
61​
62 if (oldMultiplicity <= 0 && newMultiplicity > 0) {
63 // The value wasn't present in the stream
64 // but with this change it is now present in the stream
65 result.push([value, 1])
66 } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
67 // The value was present in the stream
68 // but with this change it is no longer present in the stream
69 result.push([value, -1])
70 }
71 }
72​
73 if (result.length > 0) {
74 this.output.sendData(new MultiSet(result))
75 }
76 }
78​
79/**
80 * Removes duplicate values
81 */
82export function distinct<T>(by: (value: T) => any = (value: T) => value) {
83 return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {
84 const output = new StreamBuilder<T>(
85 stream.graph,
86 new DifferenceStreamWriter<T>()
87 )
88 const operator = new DistinctOperator<T>(
89 stream.graph.getNextOperatorId(),
90 stream.connectReader(),
91 output.writer,
92 by
93 )
94 stream.graph.addOperator(operator)
95 stream.graph.addStream(output.connectReader())
96 return output
97 }