UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

86 lines (85 loc) 3 kB
import { compileSingleRowExpression } from "../query/compiler/evaluators.js"; import { DEFAULT_COMPARE_OPTIONS, deepEquals } from "../utils.js"; function normalizeLocaleOptions(options) { return Object.fromEntries( Object.entries(options ?? {}).filter(([, value]) => value !== void 0) ); } function canonicalizeLocale(locale) { return locale === void 0 ? void 0 : Intl.getCanonicalLocales(locale)[0]; } function usesLocaleCollation(options) { return (options.stringSort ?? DEFAULT_COMPARE_OPTIONS.stringSort) === `locale`; } class BaseIndex { constructor(id, expression, name, options) { this.lookupCount = 0; this.totalLookupTime = 0; this.lastUpdated = /* @__PURE__ */ new Date(); this.hasCustomComparator = false; this.id = id; this.expression = expression; this.compareOptions = DEFAULT_COMPARE_OPTIONS; this.name = name; this.initialize(options); } // Common methods supports(operation) { return this.supportedOperations.has(operation); } get supportsRangeOptimization() { return !this.hasCustomComparator; } matchesField(fieldPath) { return this.expression.type === `ref` && this.expression.path.length === fieldPath.length && this.expression.path.every((part, i) => part === fieldPath[i]); } /** * Checks if the compare options match the index's compare options. * The direction is ignored because the index can be reversed if the direction is different. */ matchesCompareOptions(compareOptions) { const indexCompareOptions = this.compareOptions; const indexUsesLocale = usesLocaleCollation(indexCompareOptions); const requestedUsesLocale = usesLocaleCollation(compareOptions); if (indexCompareOptions.nulls !== compareOptions.nulls || indexUsesLocale !== requestedUsesLocale) { return false; } if (!indexUsesLocale || !requestedUsesLocale) { return true; } return canonicalizeLocale(indexCompareOptions.locale) === canonicalizeLocale(compareOptions.locale) && deepEquals( normalizeLocaleOptions(indexCompareOptions.localeOptions), normalizeLocaleOptions(compareOptions.localeOptions) ); } /** * Checks if the index matches the provided direction. */ matchesDirection(direction) { return this.compareOptions.direction === direction; } getStats() { return { entryCount: this.keyCount, lookupCount: this.lookupCount, averageLookupTime: this.lookupCount > 0 ? this.totalLookupTime / this.lookupCount : 0, lastUpdated: this.lastUpdated }; } evaluateIndexExpression(item) { const evaluator = this.compiledIndexEvaluator ??= compileSingleRowExpression(this.expression); return evaluator(item); } trackLookup(startTime) { const duration = performance.now() - startTime; this.lookupCount++; this.totalLookupTime += duration; } updateTimestamp() { this.lastUpdated = /* @__PURE__ */ new Date(); } } export { BaseIndex }; //# sourceMappingURL=base-index.js.map