MCPcopy Create free account
hub / github.com/TanStack/db / #handleSingleValueTransition

Method #handleSingleValueTransition

packages/db-ivm/src/indexes.ts:361–423  ·  view source on GitHub ↗

* Handle the transition from a single value to either a ValueMap or PrefixMap

(
    key: TKey,
    currentSingleValue: SingleValue<TValue>,
    newValue: TValue,
    multiplicity: number,
  )

Source from the content-addressed store, hash-verified

359 * Handle the transition from a single value to either a ValueMap or PrefixMap
360 */
361 #handleSingleValueTransition(
362 key: TKey,
363 currentSingleValue: SingleValue<TValue>,
364 newValue: TValue,
365 multiplicity: number,
366 ) {
367 const [currentValue, currentMultiplicity] = currentSingleValue
368
369 // Check for exact same value (reference equality)
370 if (currentValue === newValue) {
371 const newMultiplicity = currentMultiplicity + multiplicity
372 if (newMultiplicity === 0) {
373 this.#inner.delete(key)
374 } else {
375 this.#inner.set(key, [newValue, newMultiplicity])
376 }
377 return
378 }
379
380 // Get prefixes for both values
381 const newPrefix = getPrefix<TValue, TPrefix>(newValue)
382 const currentPrefix = getPrefix<TValue, TPrefix>(currentValue)
383
384 // Check if they're the same value by prefix/suffix comparison
385 if (
386 currentPrefix === newPrefix &&
387 (currentValue === newValue || hash(currentValue) === hash(newValue))
388 ) {
389 const newMultiplicity = currentMultiplicity + multiplicity
390 if (newMultiplicity === 0) {
391 this.#inner.delete(key)
392 } else {
393 this.#inner.set(key, [newValue, newMultiplicity])
394 }
395 return
396 }
397
398 // Different values - choose appropriate map type
399 if (currentPrefix === NO_PREFIX && newPrefix === NO_PREFIX) {
400 // Both have NO_PREFIX, use ValueMap directly
401 const valueMap = new ValueMap<TValue>()
402 valueMap.set(hash(currentValue), currentSingleValue)
403 valueMap.set(hash(newValue), [newValue, multiplicity])
404 this.#inner.set(key, valueMap)
405 } else {
406 // At least one has a prefix, use PrefixMap
407 const prefixMap = new PrefixMap<TValue, TPrefix>()
408
409 if (currentPrefix === newPrefix) {
410 // Same prefix, different suffixes - need ValueMap within PrefixMap
411 const valueMap = new ValueMap<TValue>()
412 valueMap.set(hash(currentValue), currentSingleValue)
413 valueMap.set(hash(newValue), [newValue, multiplicity])
414 prefixMap.set(currentPrefix, valueMap)
415 } else {
416 // Different prefixes - store as separate single values
417 prefixMap.set(currentPrefix, currentSingleValue)
418 prefixMap.set(newPrefix, [newValue, multiplicity])

Callers 1

addValueMethod · 0.95

Calls 4

getPrefixFunction · 0.85
hashFunction · 0.85
deleteMethod · 0.45
setMethod · 0.45

Tested by

no test coverage detected