@tanstack/db
Version:
A reactive client store for building super fast apps on sync
1 lines • 17.5 kB
Source Map (JSON)
{"version":3,"file":"basic-index.cjs","names":["BaseIndex","normalizeValue","findInsertPositionInArray","areSameValueZeroEqual","codedMessage","compareKeys","compareKeysReversed","builtInIndexResolverNames","valueMap","sortedValues","sortedExactValues","indexedKeys","addToBucket","removeFromBucket","takeFromIndex"],"sources":["../../../src/indexes/basic-index.ts"],"sourcesContent":["import { compareKeys } from '@tanstack/db-ivm'\nimport { areSameValueZeroEqual, normalizeValue } from '../utils/comparison.js'\nimport { codedMessage, devBuild } from '../error-message.js'\nimport {\n compareKeysReversed,\n findInsertPositionInArray,\n} from '../utils/array-utils.js'\nimport {\n BaseIndex,\n builtInIndexResolverNames,\n warnRemovalFailure,\n} from './base-index.js'\nimport type { IndexComparisonOptions, IndexOperation } from './base-index.js'\nimport type { RangeQueryOptions } from './btree-index.js'\n\nexport type { RangeQueryOptions } from './btree-index.js'\n\n/**\n * Options for Basic index\n */\nexport type BasicIndexOptions = IndexComparisonOptions\n\nfunction orderValue(value: unknown): unknown {\n return value instanceof Date ? value.getTime() : value\n}\n\n/**\n * Basic index using Map + sorted Array.\n *\n * - Map for O(1) equality lookups\n * - Sorted Array for O(log n) range queries via binary search\n * - O(n) updates to maintain sort order\n *\n * Simpler and smaller than BTreeIndex, good for read-heavy workloads.\n * Use BTreeIndex for write-heavy workloads with large collections.\n */\nexport class BasicIndex<\n TKey extends string | number = string | number,\n> extends BaseIndex<TKey> {\n // Map for O(1) equality lookups: indexedValue -> Set of PKs\n private valueMap = new Map<any, Set<TKey>>()\n // Sorted array of unique indexed values for range queries\n private sortedValues: Array<any> = []\n private sortedExactValues: Array<unknown> = []\n // Set of all indexed PKs\n private indexedKeys = new Set<TKey>()\n\n /**\n * Adds a value to the index\n */\n add(key: TKey, item: any): void {\n const indexedValue = this.evaluateAddedValue(key, item)\n const normalizedValue = normalizeValue(indexedValue)\n\n this.addToBucket(key, normalizedValue, indexedValue)\n this.addRangeValue(indexedValue)\n\n this.indexedKeys.add(key)\n }\n\n private addToBucket(\n key: TKey,\n normalizedValue: unknown,\n value: unknown,\n ): void {\n const keySet = this.valueMap.get(normalizedValue)\n if (keySet) {\n // Value already exists, just add the key to the set\n keySet.add(key)\n } else {\n // New value. Find its sorted position first: a comparator failure must\n // throw before the index changes.\n const orderedValue = orderValue(value)\n const insertIdx = findInsertPositionInArray(\n this.sortedValues,\n orderedValue,\n this.compareFn,\n )\n this.valueMap.set(normalizedValue, new Set([key]))\n this.sortedValues.splice(insertIdx, 0, orderedValue)\n this.sortedExactValues.splice(insertIdx, 0, normalizedValue)\n }\n }\n\n /**\n * Removes a value from the index\n */\n remove(key: TKey, item: any): void {\n let indexedValue: any\n try {\n indexedValue = this.evaluateIndexExpression(item)\n } catch (error) {\n warnRemovalFailure(key, error)\n this.indexedKeys.delete(key)\n return\n }\n\n const normalizedValue = normalizeValue(indexedValue)\n\n this.removeFromBucket(key, normalizedValue, indexedValue)\n this.removeRangeValue(indexedValue)\n\n this.indexedKeys.delete(key)\n }\n\n private removeFromBucket(\n key: TKey,\n normalizedValue: unknown,\n value: unknown,\n ): void {\n const keySet = this.valueMap.get(normalizedValue)\n if (keySet?.has(key)) {\n // The last key for this value leaves the sorted array too. Locate it\n // before any change, so a comparator failure leaves the index unchanged.\n if (keySet.size === 1) {\n const orderedValue = orderValue(value)\n let sortedIndex = findInsertPositionInArray(\n this.sortedValues,\n orderedValue,\n this.compareFn,\n )\n // Distinct equality keys may share one comparator position.\n while (\n sortedIndex < this.sortedValues.length &&\n this.compareFn(this.sortedValues[sortedIndex], orderedValue) === 0\n ) {\n if (\n areSameValueZeroEqual(\n this.sortedExactValues[sortedIndex],\n normalizedValue,\n )\n ) {\n this.sortedValues.splice(sortedIndex, 1)\n this.sortedExactValues.splice(sortedIndex, 1)\n break\n }\n sortedIndex++\n }\n this.valueMap.delete(normalizedValue)\n }\n keySet.delete(key)\n }\n }\n\n /**\n * Updates a value in the index\n */\n update(key: TKey, oldItem: any, newItem: any): void {\n let oldIndexedValue: unknown\n let newIndexedValue: unknown\n try {\n oldIndexedValue = this.evaluateIndexExpression(oldItem)\n newIndexedValue = this.evaluateIndexExpression(newItem)\n } catch {\n this.remove(key, oldItem)\n this.add(key, newItem)\n return\n }\n\n const oldValue = normalizeValue(oldIndexedValue)\n const newValue = normalizeValue(newIndexedValue)\n if (\n areSameValueZeroEqual(oldValue, newValue) &&\n this.valueMap.get(newValue)?.has(key) &&\n this.indexedKeys.has(key)\n ) {\n this.removeRangeValue(oldIndexedValue)\n this.addRangeValue(newIndexedValue)\n return\n }\n\n this.removeFromBucket(key, oldValue, oldIndexedValue)\n this.removeRangeValue(oldIndexedValue)\n this.addToBucket(key, newValue, newIndexedValue)\n this.addRangeValue(newIndexedValue)\n this.indexedKeys.add(key)\n }\n\n /**\n * Builds the index from a collection of entries\n */\n build(entries: Iterable<[TKey, any]>): void {\n this.clear()\n\n for (const [key, item] of entries) {\n const indexedValue = this.evaluateAddedValue(key, item)\n const value = normalizeValue(indexedValue)\n const keys = this.valueMap.get(value)\n if (keys) keys.add(key)\n else {\n this.valueMap.set(value, new Set([key]))\n this.sortedValues.push(orderValue(indexedValue))\n this.sortedExactValues.push(value)\n }\n this.addRangeValue(indexedValue)\n this.indexedKeys.add(key)\n }\n\n // Array.sort moves raw undefined values last without comparing them.\n // Wrap values so nulls-first comparison runs during a full build.\n const sortable = this.sortedValues.map((value, index) => ({\n value,\n exact: this.sortedExactValues[index],\n }))\n sortable.sort((left, right) => this.compareFn(left.value, right.value))\n this.sortedValues = sortable.map(({ value }) => value)\n this.sortedExactValues = sortable.map(({ exact }) => exact)\n }\n\n /**\n * Clears all data from the index\n */\n clear(): void {\n this.valueMap.clear()\n this.sortedValues = []\n this.sortedExactValues = []\n this.indexedKeys.clear()\n this.clearRangeValues()\n }\n\n lookup(operation: IndexOperation, value: any): Set<TKey> {\n const result = this.lookupSupportedOperation(operation, value)\n if (result !== undefined) return result\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Operation ${operation} not supported by BasicIndex`\n : codedMessage(100, { operation }),\n )\n }\n\n /**\n * Gets the number of indexed keys\n */\n get keyCount(): number {\n return this.indexedKeys.size\n }\n\n /**\n * Performs an equality lookup - O(1)\n */\n equalityLookup(value: any): Set<TKey> {\n const normalizedValue = normalizeValue(value)\n return this.valueMap.get(normalizedValue) ?? new Set()\n }\n\n /**\n * Performs a range query using binary search - O(log n + m)\n */\n rangeQuery(options: RangeQueryOptions = {}): Set<TKey> {\n const { from, to, fromInclusive = true, toInclusive = true } = options\n const result = new Set<TKey>()\n\n if (this.sortedValues.length === 0) {\n return result\n }\n\n const orderedFrom = orderValue(from)\n const orderedTo = orderValue(to)\n const hasFrom = `from` in options\n const hasTo = `to` in options\n\n // Find start index\n let startIdx = 0\n if (hasFrom) {\n startIdx = findInsertPositionInArray(\n this.sortedValues,\n orderedFrom,\n this.compareFn,\n )\n // Comparator-equal values form one range boundary even when they are\n // distinct equality keys.\n while (\n !fromInclusive &&\n startIdx < this.sortedValues.length &&\n this.compareFn(this.sortedValues[startIdx], orderedFrom) === 0\n ) {\n startIdx++\n }\n }\n\n // Find end index\n let endIdx = this.sortedValues.length\n if (hasTo) {\n endIdx = findInsertPositionInArray(\n this.sortedValues,\n orderedTo,\n this.compareFn,\n )\n // Include the whole comparator group at an inclusive upper boundary.\n while (\n toInclusive &&\n endIdx < this.sortedValues.length &&\n this.compareFn(this.sortedValues[endIdx], orderedTo) === 0\n ) {\n endIdx++\n }\n }\n\n // Collect all keys in range\n for (let i = startIdx; i < endIdx; i++) {\n const keys = this.valueMap.get(this.sortedExactValues[i])\n if (keys) {\n keys.forEach((key) => result.add(key))\n }\n }\n\n return result\n }\n\n /**\n * Returns the next n items in sorted order\n */\n take(n: number, from: any, filterFn?: (key: TKey) => boolean): Array<TKey> {\n const orderedFrom = orderValue(from)\n let startIdx = findInsertPositionInArray(\n this.sortedValues,\n orderedFrom,\n this.compareFn,\n )\n // Skip past the 'from' value (exclusive)\n while (\n startIdx < this.sortedValues.length &&\n this.compareFn(this.sortedValues[startIdx], orderedFrom) <= 0\n ) {\n startIdx++\n }\n\n return this.takeFromIndex(n, startIdx, 1, filterFn)\n }\n\n /**\n * Returns the next n items in reverse sorted order\n */\n takeReversed(\n n: number,\n from: any,\n filterFn?: (key: TKey) => boolean,\n ): Array<TKey> {\n const orderedFrom = orderValue(from)\n let startIdx =\n findInsertPositionInArray(\n this.sortedValues,\n orderedFrom,\n this.compareFn,\n ) - 1\n // Skip past the 'from' value (exclusive)\n while (\n startIdx >= 0 &&\n this.compareFn(this.sortedValues[startIdx], orderedFrom) >= 0\n ) {\n startIdx--\n }\n\n return this.takeFromIndex(n, startIdx, -1, filterFn)\n }\n\n /**\n * Returns the first n items in sorted order (from the start)\n */\n takeFromStart(n: number, filterFn?: (key: TKey) => boolean): Array<TKey> {\n return this.takeFromIndex(n, 0, 1, filterFn)\n }\n\n /**\n * Returns the first n items in reverse sorted order (from the end)\n */\n takeReversedFromEnd(\n n: number,\n filterFn?: (key: TKey) => boolean,\n ): Array<TKey> {\n return this.takeFromIndex(n, this.sortedValues.length - 1, -1, filterFn)\n }\n\n private takeFromIndex(\n n: number,\n startIndex: number,\n step: 1 | -1,\n filterFn?: (key: TKey) => boolean,\n ): Array<TKey> {\n const result: Array<TKey> = []\n let index = startIndex\n while (\n index >= 0 &&\n index < this.sortedValues.length &&\n result.length < n\n ) {\n const groupValue = this.sortedValues[index]\n const groupKeys: Array<TKey> = []\n do {\n for (const key of this.valueMap.get(this.sortedExactValues[index]) ??\n []) {\n groupKeys.push(key)\n }\n index += step\n } while (\n index >= 0 &&\n index < this.sortedValues.length &&\n this.compareFn(this.sortedValues[index], groupValue) === 0\n )\n groupKeys.sort(step === 1 ? compareKeys : compareKeysReversed)\n for (const key of groupKeys) {\n if (filterFn?.(key) ?? true) result.push(key)\n if (result.length >= n) break\n }\n }\n return result\n }\n}\n\nbuiltInIndexResolverNames.set(BasicIndex, `BasicIndex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