MCPcopy Index your code
hub / github.com/TanStack/db / indexOf

Method indexOf

packages/db/src/SortedMap.ts:36–83  ·  view source on GitHub ↗

* Finds the index where a key-value pair should be inserted to maintain sort order. * Uses binary search to find the correct position based on the value (if comparator provided), * with key-based tie-breaking for deterministic ordering when values compare as equal. * If no comparator is pro

(key: TKey, value: TValue)

Source from the content-addressed store, hash-verified

34 * @returns The index where the key should be inserted
35 */
36 private indexOf(key: TKey, value: TValue): number {
37 let left = 0
38 let right = this.sortedKeys.length
39
40 // Fast path: no comparator means sort by key only
41 if (!this.comparator) {
42 while (left < right) {
43 const mid = Math.floor((left + right) / 2)
44 const midKey = this.sortedKeys[mid]!
45 const keyComparison = compareKeys(key, midKey)
46 if (keyComparison < 0) {
47 right = mid
48 } else if (keyComparison > 0) {
49 left = mid + 1
50 } else {
51 return mid
52 }
53 }
54 return left
55 }
56
57 // With comparator: sort by value first, then key as tie-breaker
58 while (left < right) {
59 const mid = Math.floor((left + right) / 2)
60 const midKey = this.sortedKeys[mid]!
61 const midValue = this.map.get(midKey)!
62 const valueComparison = this.comparator(value, midValue)
63
64 if (valueComparison < 0) {
65 right = mid
66 } else if (valueComparison > 0) {
67 left = mid + 1
68 } else {
69 // Values are equal, use key as tie-breaker for deterministic ordering
70 const keyComparison = compareKeys(key, midKey)
71 if (keyComparison < 0) {
72 right = mid
73 } else if (keyComparison > 0) {
74 left = mid + 1
75 } else {
76 // Same key (shouldn't happen during insert, but handle for lookups)
77 return mid
78 }
79 }
80 }
81
82 return left
83 }
84
85 /**
86 * Sets a key-value pair in the map and maintains sort order

Callers 2

setMethod · 0.95
deleteMethod · 0.95

Calls 2

compareKeysFunction · 0.90
getMethod · 0.45

Tested by

no test coverage detected