MCPcopy Create free account
hub / github.com/TanStack/db / insert

Method insert

packages/db-ivm/src/operators/topKArray.ts:154–196  ·  view source on GitHub ↗
(value: V)

Source from the content-addressed store, hash-verified

152 }
153
154 insert(value: V): TopKChanges<V> {
155 const result: TopKChanges<V> = { moveIn: null, moveOut: null }
156
157 // Lookup insert position
158 const index = this.#findIndex(value)
159 // Generate fractional index based on the fractional indices of the elements before and after it
160 const indexBefore =
161 index === 0 ? null : getIndex(this.#sortedValues[index - 1]!)
162 const indexAfter =
163 index === this.#sortedValues.length
164 ? null
165 : getIndex(this.#sortedValues[index]!)
166 const fractionalIndex = generateKeyBetween(indexBefore, indexAfter)
167
168 // Insert the value at the correct position
169 const val = indexedValue(value, fractionalIndex)
170 // Splice is O(n) where n = all elements in the collection (i.e. n >= k) !
171 this.#sortedValues.splice(index, 0, val)
172
173 // Check if the topK changed
174 if (index < this.#topKEnd) {
175 // The inserted element is either before the top K or within the top K
176 // If it is before the top K then it moves the element that was right before the topK into the topK
177 // If it is within the top K then the inserted element moves into the top K
178 // In both cases the last element of the old top K now moves out of the top K
179 const moveInIndex = Math.max(index, this.#topKStart)
180 if (moveInIndex < this.#sortedValues.length) {
181 // We actually have a topK
182 // because in some cases there may not be enough elements in the array to reach the start of the topK
183 // e.g. [1, 2, 3] with K = 2 and offset = 3 does not have a topK
184 result.moveIn = this.#sortedValues[moveInIndex]!
185
186 // We need to remove the element that falls out of the top K
187 // The element that falls out of the top K has shifted one to the right
188 // because of the element we inserted, so we find it at index topKEnd
189 if (this.#topKEnd < this.#sortedValues.length) {
190 result.moveOut = this.#sortedValues[this.#topKEnd]!
191 }
192 }
193 }
194
195 return result
196 }
197
198 /**
199 * Deletes a value that may or may not be in the topK.

Callers 3

persisted.test.tsFile · 0.45
processElementMethod · 0.45

Calls 3

#findIndexMethod · 0.95
getIndexFunction · 0.85
indexedValueFunction · 0.85

Tested by

no test coverage detected