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

multiset.ts

191 lines6.2 KB

1import { chunkedArrayPush } 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 return consolidateKeyed(inner)
98 }
99​
100 // Unkeyed data of a single primitive type is its own identity, and the
101 // result holds the Map key, so -0 becomes 0. Anything else is compared
102 // structurally by hash.
103 let primitiveType: string | undefined
104 const requireHash = inner.some(([data]) => {
105 const type = typeof data
106 if (type !== `string` && type !== `number`) return true
107 primitiveType ??= type
108 return type !== primitiveType
109 })
110 return requireHash
111 ? consolidateBy(inner, hash)
112 : consolidateBy(inner, (data) => data, true)
113 }
114​
115 extend(other: MultiSet<T> | MultiSetArray<T>): void {
116 const otherArray = other instanceof MultiSet ? other.getInner() : other
117 chunkedArrayPush(this.#inner, otherArray)
118 }
119​
120 add(item: T, multiplicity: number): void {
121 if (multiplicity !== 0) {
122 this.#inner.push([item, multiplicity])
123 }
124 }
125​
126 getInner(): MultiSetArray<T> {
127 return this.#inner
128 }
130​
131/**
132 * Consolidates `[key, value]` records. `Map` keys compare by SameValueZero,
133 * which is the identity the keyed rule asks for: primitives by value (`-0`
134 * equals `0`, `NaN` equals `NaN`) and objects by reference. A join tuple is
135 * looked up element by element, and leaves and tuples use separate maps.
136 */
137function consolidateKeyed<T>(inner: MultiSetArray<T>): MultiSet<T> {
138 const leaves = new Map<unknown, Map<unknown, [T, number]>>()
139 const tuples = new Map<unknown, Map<unknown, Map<unknown, [T, number]>>>()
140 const entries: MultiSetArray<T> = []
141 for (const [data, multiplicity] of inner) {
142 const [key, value] = data as [string | number, unknown]
143 let entry: [T, number] | undefined
144 if (Array.isArray(value) && value.length === 2) {
145 let byFirst = tuples.get(key)
146 if (!byFirst) tuples.set(key, (byFirst = new Map()))
147 let bySecond = byFirst.get(value[0])
148 if (!bySecond) byFirst.set(value[0], (bySecond = new Map()))
149 entry = bySecond.get(value[1])
150 if (!entry) {
151 bySecond.set(value[1], (entry = [data, 0]))
152 entries.push(entry)
153 }
154 } else {
155 let byValue = leaves.get(key)
156 if (!byValue) leaves.set(key, (byValue = new Map()))
157 entry = byValue.get(value)
158 if (!entry) {
159 byValue.set(value, (entry = [data, 0]))
160 entries.push(entry)
161 }
162 }
163 entry[1] += multiplicity
164 }
165 return new MultiSet(entries.filter(([, multiplicity]) => multiplicity !== 0))
167​
168/**
169 * Sums multiplicities of records with the same identity, keeping the first
170 * record seen for each identity (or its Map key, which writes -0 as 0, when
171 * `keepIdentity` is set) and dropping records whose sum is zero.
172 */
173function consolidateBy<T>(
174 inner: MultiSetArray<T>,
175 identityOf: (data: T) => unknown,
176 keepIdentity = false,
177): MultiSet<T> {
178 const consolidated = new Map<unknown, [T, number]>()
179 for (const [data, multiplicity] of inner) {
180 const identity = identityOf(data)
181 const entry = consolidated.get(identity)
182 if (entry) entry[1] += multiplicity
183 else consolidated.set(identity, [data, multiplicity])
184 }
185 const result: MultiSetArray<T> = []
186 for (const [identity, [data, multiplicity]] of consolidated) {
187 if (multiplicity !== 0)
188 result.push([keepIdentity ? (identity as T) : data, multiplicity])
189 }
190 return new MultiSet(result)