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

multiset.ts

168 lines5.4 KB

1import { chunkedArrayPush, getStringId } from './utils.js'
2import { hash } from './hashing/index.js'
3​
4export type MultiSetArray<T> = Array<[T, number]>
5export type KeyedData<T> = [key: string, value: T]
6​
7/**
8 * A multiset of data.
9 */
10export class MultiSet<T> {
11 #inner: MultiSetArray<T>
12​
13 constructor(data: MultiSetArray<T> = []) {
14 this.#inner = data
15 }
16​
17 toString(indent = false): string {
18 return `MultiSet(${JSON.stringify(this.#inner, null, indent ? 2 : undefined)})`
19 }
20​
21 toJSON(): string {
22 return JSON.stringify(Array.from(this.getInner()))
23 }
24​
25 static fromJSON<U>(json: string): MultiSet<U> {
26 return new MultiSet(JSON.parse(json))
27 }
28​
29 /**
30 * Apply a function to all records in the collection.
31 */
32 map<U>(f: (data: T) => U): MultiSet<U> {
33 return new MultiSet(
34 this.#inner.map(([data, multiplicity]) => [f(data), multiplicity]),
35 )
36 }
37​
38 /**
39 * Filter out records for which a function f(record) evaluates to False.
40 */
41 filter(f: (data: T) => boolean): MultiSet<T> {
42 return new MultiSet(this.#inner.filter(([data, _]) => f(data)))
43 }
44​
45 /**
46 * Negate all multiplicities in the collection.
47 */
48 negate(): MultiSet<T> {
49 return new MultiSet(
50 this.#inner.map(([data, multiplicity]) => [data, -multiplicity]),
51 )
52 }
53​
54 /**
55 * Concatenate two collections together.
56 */
57 concat(other: MultiSet<T>): MultiSet<T> {
58 const out: MultiSetArray<T> = []
59 chunkedArrayPush(out, this.#inner)
60 chunkedArrayPush(out, other.getInner())
61 return new MultiSet(out)
62 }
63​
64 /**
65 * Produce as output a collection that is logically equivalent to the input
66 * but which combines identical instances of the same record into one
67 * (record, multiplicity) pair.
68 *
69 * Record identity depends on the shape of the whole multiset:
70 *
71 * - Keyed: every record is a `[key, value]` pair with a string or number
72 * key. Keys and primitive values compare by value, and object values by
73 * reference. A value that is an array of length 2 is a join tuple, and
74 * its two elements compare by the same rule.
75 * - Unkeyed, one primitive type: every record is a string, or every record
76 * is a number. Records compare as `Map` keys do, and a `-0` record is
77 * returned as `0`.
78 * - Otherwise, records compare by structure (`hash`).
79 *
80 * Each identity keeps its first record in input order with the summed
81 * multiplicity. Identities whose sum is zero are dropped. The input is not
82 * changed.
83 */
84 consolidate(): MultiSet<T> {
85 const inner = this.#inner
86 // Keyed multisets hold [string | number key, value] pairs. Their values are
87 // compared by reference, which avoids hashing. Join tuples (values of
88 // length 2) are unpacked so ['A', null] and [null, 'X'] stay distinct.
89 if (
90 inner.every(
91 ([data]) =>
92 Array.isArray(data) &&
93 data.length === 2 &&
94 (typeof data[0] === `string` || typeof data[0] === `number`),
95 )
96 ) {
97 const referenceIds = new Map<object | symbol, number>()
98 return consolidateBy(inner, (data) => {
99 const [key, value] = data as [string | number, unknown]
100 // Length prefixes keep user text from crossing component boundaries.
101 let valueId: string
102 if (Array.isArray(value) && value.length === 2) {
103 const firstId = getStringId(value[0], referenceIds)
104 const secondId = getStringId(value[1], referenceIds)
105 valueId = `tuple_${firstId.length}:${firstId}${secondId}`
106 } else {
107 valueId = `leaf_${getStringId(value, referenceIds)}`
108 }
109 const keyId = getStringId(key, referenceIds)
110 return `${keyId.length}:${keyId}${valueId}`
111 })
112 }
113​
114 // Unkeyed data of a single primitive type is its own identity, and the
115 // result holds the Map key, so -0 becomes 0. Anything else is compared
116 // structurally by hash.
117 let primitiveType: string | undefined
118 const requireHash = inner.some(([data]) => {
119 const type = typeof data
120 if (type !== `string` && type !== `number`) return true
121 primitiveType ??= type
122 return type !== primitiveType
123 })
124 return requireHash
125 ? consolidateBy(inner, hash)
126 : consolidateBy(inner, (data) => data, true)
127 }
128​
129 extend(other: MultiSet<T> | MultiSetArray<T>): void {
130 const otherArray = other instanceof MultiSet ? other.getInner() : other
131 chunkedArrayPush(this.#inner, otherArray)
132 }
133​
134 add(item: T, multiplicity: number): void {
135 if (multiplicity !== 0) {
136 this.#inner.push([item, multiplicity])
137 }
138 }
139​
140 getInner(): MultiSetArray<T> {
141 return this.#inner
142 }
144​
145/**
146 * Sums multiplicities of records with the same identity, keeping the first
147 * record seen for each identity (or its Map key, which writes -0 as 0, when
148 * `keepIdentity` is set) and dropping records whose sum is zero.
149 */
150function consolidateBy<T>(
151 inner: MultiSetArray<T>,
152 identityOf: (data: T) => unknown,
153 keepIdentity = false,
154): MultiSet<T> {
155 const consolidated = new Map<unknown, [T, number]>()
156 for (const [data, multiplicity] of inner) {
157 const identity = identityOf(data)
158 const entry = consolidated.get(identity)
159 if (entry) entry[1] += multiplicity
160 else consolidated.set(identity, [data, multiplicity])
161 }
162 const result: MultiSetArray<T> = []
163 for (const [identity, [data, multiplicity]] of consolidated) {
164 if (multiplicity !== 0)
165 result.push([keepIdentity ? (identity as T) : data, multiplicity])
166 }
167 return new MultiSet(result)