@tanstack/db-ivm
Version:
Incremental View Maintenance for TanStack DB based on Differential Dataflow
1 lines • 3.27 kB
Source Map (JSON)
{"version":3,"file":"valueIndex.cjs","sources":["../../src/valueIndex.ts"],"sourcesContent":["import { hash } from \"./hashing/index.js\"\n\n/**\n * A map from a difference collection trace's keys -> (value, multiplicities) that changed.\n * Used in operations like join and reduce where the operation needs to\n * exploit the key-value structure of the data to run efficiently.\n */\nexport class ValueIndex<K, V> {\n #inner: Map<K, [V, number]> // Maps key to the value and its multiplicity\n\n constructor() {\n this.#inner = new Map()\n }\n\n toString(indent = false): string {\n return `ValueIndex(${JSON.stringify(\n [...this.#inner.entries()],\n undefined,\n indent ? 2 : undefined\n )})`\n }\n\n get(key: K): [V, number] | undefined {\n return this.#inner.get(key)\n }\n\n getMultiplicity(key: K): number {\n return this.get(key)?.[1] ?? 0\n }\n\n entries() {\n return this.#inner.entries()\n }\n\n has(key: K): boolean {\n return this.#inner.has(key)\n }\n\n delete(key: K): void {\n this.#inner.delete(key)\n }\n\n get size(): number {\n return this.#inner.size\n }\n\n addValue(key: K, v: [V, number]): void {\n const [value, multiplicity] = v\n\n if (multiplicity === 0) {\n return\n }\n\n if (this.has(key)) {\n const [currValue, currMultiplicity] = this.get(key)!\n if (hash(value) === hash(currValue)) {\n // Update the multiplicity\n this.#setMultiplicity(key, value, currMultiplicity + multiplicity)\n return\n }\n // Different value, not allowed.\n // ValueIndex only supports one value per key.\n throw new Error(\n `Cannot add value for key ${key} because it already exists in ValueIndex with a different value`\n )\n }\n\n this.#inner.set(key, [value, multiplicity])\n }\n\n #setMultiplicity(key: K, value: V, multiplicity: number): void {\n if (multiplicity === 0) {\n this.#inner.delete(key)\n } else {\n this.#inner.set(key, [value, multiplicity])\n }\n }\n}\n"],"names":["hash"],"mappings":";;;;;;;;;;;;AAOO,MAAM,WAAiB;AAAA;AAAA,EAG5B,cAAc;AAHT;AACL;AAGE,uBAAK,4BAAa,IAAA;AAAA,EACpB;AAAA,EAEA,SAAS,S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