| 21 | * Only works with number and string values that are naturally comparable. |
| 22 | */ |
| 23 | export class BTreeIndex implements Index { |
| 24 | public readonly type = "btree" as const; |
| 25 | public readonly label: string; |
| 26 | public readonly property: string; |
| 27 | |
| 28 | /** |
| 29 | * Sorted array of entries. |
| 30 | */ |
| 31 | #entries: IndexEntry[] = []; |
| 32 | |
| 33 | /** |
| 34 | * Map from element ID to its current value for efficient updates. |
| 35 | */ |
| 36 | #elementValues: Map<ElementId, number | string> = new Map(); |
| 37 | |
| 38 | /** |
| 39 | * Optional custom comparator. |
| 40 | */ |
| 41 | #comparator: ((a: number | string, b: number | string) => number) | undefined; |
| 42 | |
| 43 | public constructor( |
| 44 | label: string, |
| 45 | property: string, |
| 46 | comparator?: (a: number | string, b: number | string) => number, |
| 47 | ) { |
| 48 | this.label = label; |
| 49 | this.property = property; |
| 50 | this.#comparator = comparator; |
| 51 | } |
| 52 | |
| 53 | #compare(a: number | string, b: number | string): number { |
| 54 | if (this.#comparator) { |
| 55 | return this.#comparator(a, b); |
| 56 | } |
| 57 | if (a < b) return -1; |
| 58 | if (a > b) return 1; |
| 59 | return 0; |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Find the insertion point for a value using binary search. |
| 64 | */ |
| 65 | #findInsertionPoint(value: number | string): number { |
| 66 | let low = 0; |
| 67 | let high = this.#entries.length; |
| 68 | |
| 69 | while (low < high) { |
| 70 | const mid = (low + high) >>> 1; |
| 71 | if (this.#compare(this.#entries[mid]!.value, value) < 0) { |
| 72 | low = mid + 1; |
| 73 | } else { |
| 74 | high = mid; |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | return low; |
| 79 | } |
| 80 |
nothing calls this directly
no outgoing calls
no test coverage detected