* Private method for consolidating keyed multisets where keys are strings/numbers * and values are compared by reference equality. * * This method provides significant performance improvements over the hash-based approach * by using WeakMap for object reference tracking and avoiding expe
()
| 94 | * we unpack them and compare each element individually to maintain proper equality semantics. |
| 95 | */ |
| 96 | #consolidateKeyed(): MultiSet<T> { |
| 97 | const consolidated = new Map<string, number>() |
| 98 | const values = new Map<string, T>() |
| 99 | |
| 100 | // Use global object ID generator for consistent reference equality |
| 101 | |
| 102 | /** |
| 103 | * Special handler for tuples (arrays of length 2) commonly produced by join operations. |
| 104 | * Unpacks the tuple and generates an ID based on both elements to ensure proper |
| 105 | * consolidation of join results like ['A', null] and [null, 'X']. |
| 106 | */ |
| 107 | const getTupleId = (tuple: Array<any>): string => { |
| 108 | if (tuple.length !== 2) { |
| 109 | throw new Error(`Expected tuple of length 2`) |
| 110 | } |
| 111 | const [first, second] = tuple |
| 112 | return `${globalObjectIdGenerator.getStringId(first)}|${globalObjectIdGenerator.getStringId(second)}` |
| 113 | } |
| 114 | |
| 115 | // Process each item in the multiset |
| 116 | for (const [data, multiplicity] of this.#inner) { |
| 117 | // Verify this is still a keyed item (should be [key, value] pair) |
| 118 | if (!Array.isArray(data) || data.length !== 2) { |
| 119 | // Found non-keyed item, fall back to unkeyed consolidation |
| 120 | return this.#consolidateUnkeyed() |
| 121 | } |
| 122 | |
| 123 | const [key, value] = data |
| 124 | |
| 125 | // Verify key is string or number as expected for keyed multisets |
| 126 | if (typeof key !== `string` && typeof key !== `number`) { |
| 127 | // Found non-string/number key, fall back to unkeyed consolidation |
| 128 | return this.#consolidateUnkeyed() |
| 129 | } |
| 130 | |
| 131 | // Generate value ID with special handling for join tuples |
| 132 | let valueId: string |
| 133 | if (Array.isArray(value) && value.length === 2) { |
| 134 | // Special case: value is a tuple from join operations |
| 135 | valueId = getTupleId(value) |
| 136 | } else { |
| 137 | // Regular case: use reference/value equality |
| 138 | valueId = globalObjectIdGenerator.getStringId(value) |
| 139 | } |
| 140 | |
| 141 | // Create composite key and consolidate |
| 142 | const compositeKey = key + `|` + valueId |
| 143 | consolidated.set( |
| 144 | compositeKey, |
| 145 | (consolidated.get(compositeKey) || 0) + multiplicity, |
| 146 | ) |
| 147 | |
| 148 | // Store the original data for the first occurrence |
| 149 | if (!values.has(compositeKey)) { |
| 150 | values.set(compositeKey, data as T) |
| 151 | } |
| 152 | } |
| 153 |
no test coverage detected