@tanstack/db-ivm 0.1.8 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/d2.cjs +25 -49
- package/dist/cjs/d2.cjs.map +1 -1
- package/dist/cjs/graph.cjs +8 -20
- package/dist/cjs/graph.cjs.map +1 -1
- package/dist/cjs/indexes.cjs +118 -79
- package/dist/cjs/indexes.cjs.map +1 -1
- package/dist/cjs/indexes.d.cts +23 -0
- package/dist/cjs/multiset.cjs +106 -115
- package/dist/cjs/multiset.cjs.map +1 -1
- package/dist/cjs/multiset.d.cts +1 -0
- package/dist/cjs/operators/debug.cjs +5 -15
- package/dist/cjs/operators/debug.cjs.map +1 -1
- package/dist/cjs/operators/distinct.cjs +11 -22
- package/dist/cjs/operators/distinct.cjs.map +1 -1
- package/dist/cjs/operators/filter.cjs +3 -12
- package/dist/cjs/operators/filter.cjs.map +1 -1
- package/dist/cjs/operators/filterBy.cjs.map +1 -1
- package/dist/cjs/operators/filterBy.d.cts +1 -2
- package/dist/cjs/operators/groupBy.cjs +13 -12
- package/dist/cjs/operators/groupBy.cjs.map +1 -1
- package/dist/cjs/operators/groupBy.d.cts +7 -4
- package/dist/cjs/operators/join.cjs +104 -93
- package/dist/cjs/operators/join.cjs.map +1 -1
- package/dist/cjs/operators/join.d.cts +11 -8
- package/dist/cjs/operators/map.cjs +3 -12
- package/dist/cjs/operators/map.cjs.map +1 -1
- package/dist/cjs/operators/orderBy.cjs +10 -10
- package/dist/cjs/operators/orderBy.cjs.map +1 -1
- package/dist/cjs/operators/orderBy.d.cts +1 -2
- package/dist/cjs/operators/output.cjs +3 -12
- package/dist/cjs/operators/output.cjs.map +1 -1
- package/dist/cjs/operators/reduce.cjs +11 -22
- package/dist/cjs/operators/reduce.cjs.map +1 -1
- package/dist/cjs/operators/tap.cjs +3 -12
- package/dist/cjs/operators/tap.cjs.map +1 -1
- package/dist/cjs/operators/topK.cjs +4 -4
- package/dist/cjs/operators/topK.cjs.map +1 -1
- package/dist/cjs/operators/topK.d.cts +1 -2
- package/dist/cjs/operators/topKWithFractionalIndex.cjs +56 -75
- package/dist/cjs/operators/topKWithFractionalIndex.cjs.map +1 -1
- package/dist/esm/d2.js +25 -49
- package/dist/esm/d2.js.map +1 -1
- package/dist/esm/graph.js +8 -20
- package/dist/esm/graph.js.map +1 -1
- package/dist/esm/indexes.d.ts +23 -0
- package/dist/esm/indexes.js +118 -79
- package/dist/esm/indexes.js.map +1 -1
- package/dist/esm/multiset.d.ts +1 -0
- package/dist/esm/multiset.js +106 -115
- package/dist/esm/multiset.js.map +1 -1
- package/dist/esm/operators/debug.js +5 -15
- package/dist/esm/operators/debug.js.map +1 -1
- package/dist/esm/operators/distinct.js +11 -22
- package/dist/esm/operators/distinct.js.map +1 -1
- package/dist/esm/operators/filter.js +3 -12
- package/dist/esm/operators/filter.js.map +1 -1
- package/dist/esm/operators/filterBy.d.ts +1 -2
- package/dist/esm/operators/filterBy.js.map +1 -1
- package/dist/esm/operators/groupBy.d.ts +7 -4
- package/dist/esm/operators/groupBy.js +13 -12
- package/dist/esm/operators/groupBy.js.map +1 -1
- package/dist/esm/operators/join.d.ts +11 -8
- package/dist/esm/operators/join.js +104 -93
- package/dist/esm/operators/join.js.map +1 -1
- package/dist/esm/operators/map.js +3 -12
- package/dist/esm/operators/map.js.map +1 -1
- package/dist/esm/operators/orderBy.d.ts +1 -2
- package/dist/esm/operators/orderBy.js +10 -10
- package/dist/esm/operators/orderBy.js.map +1 -1
- package/dist/esm/operators/output.js +3 -12
- package/dist/esm/operators/output.js.map +1 -1
- package/dist/esm/operators/reduce.js +11 -22
- package/dist/esm/operators/reduce.js.map +1 -1
- package/dist/esm/operators/tap.js +3 -12
- package/dist/esm/operators/tap.js.map +1 -1
- package/dist/esm/operators/topK.d.ts +1 -2
- package/dist/esm/operators/topK.js +4 -4
- package/dist/esm/operators/topK.js.map +1 -1
- package/dist/esm/operators/topKWithFractionalIndex.js +56 -75
- package/dist/esm/operators/topKWithFractionalIndex.js.map +1 -1
- package/package.json +1 -1
- package/src/indexes.ts +54 -0
- package/src/multiset.ts +6 -0
- package/src/operators/filterBy.ts +1 -2
- package/src/operators/groupBy.ts +38 -18
- package/src/operators/join.ts +249 -139
- package/src/operators/orderBy.ts +1 -2
- package/src/operators/topK.ts +1 -2
package/dist/cjs/indexes.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"indexes.cjs","sources":["../../src/indexes.ts"],"sourcesContent":["/**\n * # Optimized Index Data Structure\n *\n * Multi-level index that adapts storage strategy based on data patterns to minimize memory\n * usage, eliminate wasteful lookups, and avoid hashing whenever possible.\n *\n * ## Storage Strategy\n *\n * **Single value**: `IndexMap['key'] → [value, multiplicity]` (no hashing needed)\n *\n * **Multiple unprefixed values**: Direct ValueMap (avoids NO_PREFIX lookup)\n * ```\n * IndexMap['key'] → ValueMap { hash(value1) → [value1, mult1], ... }\n * ```\n *\n * **Values with prefixes**: PrefixMap uses prefix keys directly (no hashing)\n * ```\n * IndexMap['key'] → PrefixMap { 'prefix1' → [value1, mult1], NO_PREFIX → ValueMap{...} }\n * ```\n *\n * **Multiple values per prefix**: ValueMap within PrefixMap (hash only suffixes)\n * ```\n * PrefixMap['prefix'] → ValueMap { hash(suffix1) → [full_value1, mult1], ... }\n * ```\n *\n * ## Dynamic Evolution\n *\n * Structure automatically evolves as data is added:\n * - Single → ValueMap (when both values unprefixed)\n * - Single → PrefixMap (when at least one prefixed)\n * - ValueMap → PrefixMap (adding prefixed value to unprefixed)\n *\n * Prefixes extracted from array values: `['prefix', 'suffix']` → prefix='prefix'\n */\n\nimport { MultiSet } from \"./multiset.js\"\nimport { hash } from \"./hashing/index.js\"\nimport type { Hash } from \"./hashing/index.js\"\n\n// We use a symbol to represent the absence of a prefix, unprefixed values a stored\n// against this key.\nconst NO_PREFIX = Symbol(`NO_PREFIX`)\ntype NO_PREFIX = typeof NO_PREFIX\n\n// A single value is a tuple of the value and the multiplicity.\ntype SingleValue<TValue> = [TValue, number]\n\n// Base map type for the index. Stores single values, prefix maps, or value maps against a key.\ntype IndexMap<TKey, TValue, TPrefix> = Map<\n TKey,\n SingleValue<TValue> | PrefixMap<TValue, TPrefix> | ValueMap<TValue>\n>\n\n// Second level map type for the index, stores single values or value maps against a prefix.\nclass PrefixMap<TValue, TPrefix> extends Map<\n TPrefix | NO_PREFIX,\n SingleValue<TValue> | ValueMap<TValue>\n> {\n /**\n * Add a value to the PrefixMap. Returns true if the map becomes empty after the operation.\n */\n addValue(value: TValue, multiplicity: number): boolean {\n if (multiplicity === 0) return this.size === 0\n\n const prefix = getPrefix<TValue, TPrefix>(value)\n const valueMapOrSingleValue = this.get(prefix)\n\n if (isSingleValue(valueMapOrSingleValue)) {\n const [currentValue, currentMultiplicity] = valueMapOrSingleValue\n const currentPrefix = getPrefix<TValue, TPrefix>(currentValue)\n\n if (currentPrefix !== prefix) {\n throw new Error(`Mismatching prefixes, this should never happen`)\n }\n\n if (currentValue === value || hash(currentValue) === hash(value)) {\n // Same value, update multiplicity\n const newMultiplicity = currentMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.delete(prefix)\n } else {\n this.set(prefix, [value, newMultiplicity])\n }\n } else {\n // Different suffixes, need to create ValueMap\n const valueMap = new ValueMap<TValue>()\n valueMap.set(hash(currentValue), valueMapOrSingleValue)\n valueMap.set(hash(value), [value, multiplicity])\n this.set(prefix, valueMap)\n }\n } else if (valueMapOrSingleValue === undefined) {\n // No existing value for this prefix\n this.set(prefix, [value, multiplicity])\n } else {\n // Existing ValueMap\n const isEmpty = valueMapOrSingleValue.addValue(value, multiplicity)\n if (isEmpty) {\n this.delete(prefix)\n }\n }\n\n return this.size === 0\n }\n}\n\n// Third level map type for the index, stores single values or value maps against a hash.\nclass ValueMap<TValue> extends Map<Hash, [TValue, number]> {\n /**\n * Add a value to the ValueMap. Returns true if the map becomes empty after the operation.\n * @param value - The full value to store\n * @param multiplicity - The multiplicity to add\n * @param hashKey - Optional hash key to use instead of hashing the full value (used when in PrefixMap context)\n */\n addValue(value: TValue, multiplicity: number): boolean {\n if (multiplicity === 0) return this.size === 0\n\n const key = hash(value)\n const currentValue = this.get(key)\n\n if (currentValue) {\n const [, currentMultiplicity] = currentValue\n const newMultiplicity = currentMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.delete(key)\n } else {\n this.set(key, [value, newMultiplicity])\n }\n } else {\n this.set(key, [value, multiplicity])\n }\n\n return this.size === 0\n }\n}\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 Index<TKey, TValue, TPrefix = any> {\n /*\n * This index maintains a nested map of keys -> (value, multiplicities), where:\n * - initially the values are stored against the key as a single value tuple\n * - when a key gets additional values, the values are stored against the key in a\n * prefix map\n * - the prefix is extract where possible from values that are structured as\n * [rowPrimaryKey, rowValue], as they are in the Tanstack DB query pipeline.\n * - only when there are multiple values for a given prefix do we fall back to a\n * hash to identify identical values, storing them in a third level value map.\n */\n #inner: IndexMap<TKey, TValue, TPrefix>\n\n constructor() {\n this.#inner = new Map()\n }\n\n /**\n * This method returns a string representation of the index.\n * @param indent - Whether to indent the string representation.\n * @returns A string representation of the index.\n */\n toString(indent = false): string {\n return `Index(${JSON.stringify(\n [...this.entries()],\n undefined,\n indent ? 2 : undefined\n )})`\n }\n\n /**\n * The size of the index.\n */\n get size(): number {\n return this.#inner.size\n }\n\n /**\n * This method checks if the index has a given key.\n * @param key - The key to check.\n * @returns True if the index has the key, false otherwise.\n */\n has(key: TKey): boolean {\n return this.#inner.has(key)\n }\n\n /**\n * This method returns all values for a given key.\n * @param key - The key to get the values for.\n * @returns An array of value tuples [value, multiplicity].\n */\n get(key: TKey): Array<[TValue, number]> {\n return [...this.getIterator(key)]\n }\n\n /**\n * This method returns an iterator over all values for a given key.\n * @param key - The key to get the values for.\n * @returns An iterator of value tuples [value, multiplicity].\n */\n *getIterator(key: TKey): Iterable<[TValue, number]> {\n const mapOrSingleValue = this.#inner.get(key)\n if (isSingleValue(mapOrSingleValue)) {\n yield mapOrSingleValue\n } else if (mapOrSingleValue === undefined) {\n return\n } else if (mapOrSingleValue instanceof ValueMap) {\n // Direct ValueMap - all values have NO_PREFIX\n for (const valueTuple of mapOrSingleValue.values()) {\n yield valueTuple\n }\n } else {\n // PrefixMap - iterate through all prefixes\n for (const singleValueOrValueMap of mapOrSingleValue.values()) {\n if (isSingleValue(singleValueOrValueMap)) {\n yield singleValueOrValueMap\n } else {\n for (const valueTuple of singleValueOrValueMap.values()) {\n yield valueTuple\n }\n }\n }\n }\n }\n\n /**\n * This returns an iterator that iterates over all key-value pairs.\n * @returns An iterable of all key-value pairs (and their multiplicities) in the index.\n */\n *entries(): Iterable<[TKey, [TValue, number]]> {\n for (const key of this.#inner.keys()) {\n for (const valueTuple of this.getIterator(key)) {\n yield [key, valueTuple]\n }\n }\n }\n\n /**\n * This method only iterates over the keys and not over the values.\n * Hence, it is more efficient than the `#entries` method.\n * It returns an iterator that you can use if you need to iterate over the values for a given key.\n * @returns An iterator of all *keys* in the index and their corresponding value iterator.\n */\n *entriesIterators(): Iterable<[TKey, Iterable<[TValue, number]>]> {\n for (const key of this.#inner.keys()) {\n yield [key, this.getIterator(key)]\n }\n }\n\n /**\n * This method adds a value to the index.\n * @param key - The key to add the value to.\n * @param valueTuple - The value tuple [value, multiplicity] to add to the index.\n */\n addValue(key: TKey, valueTuple: SingleValue<TValue>) {\n const [value, multiplicity] = valueTuple\n // If the multiplicity is 0, do nothing\n if (multiplicity === 0) return\n\n const mapOrSingleValue = this.#inner.get(key)\n\n if (mapOrSingleValue === undefined) {\n // First value for this key\n this.#inner.set(key, valueTuple)\n return\n }\n\n if (isSingleValue(mapOrSingleValue)) {\n // Handle transition from single value to map\n this.#handleSingleValueTransition(\n key,\n mapOrSingleValue,\n value,\n multiplicity\n )\n return\n }\n\n if (mapOrSingleValue instanceof ValueMap) {\n // Handle existing ValueMap\n const prefix = getPrefix<TValue, TPrefix>(value)\n if (prefix !== NO_PREFIX) {\n // Convert ValueMap to PrefixMap since we have a prefixed value\n const prefixMap = new PrefixMap<TValue, TPrefix>()\n prefixMap.set(NO_PREFIX, mapOrSingleValue)\n prefixMap.set(prefix, valueTuple)\n this.#inner.set(key, prefixMap)\n } else {\n // Add to existing ValueMap\n const isEmpty = mapOrSingleValue.addValue(value, multiplicity)\n if (isEmpty) {\n this.#inner.delete(key)\n }\n }\n } else {\n // Handle existing PrefixMap\n const isEmpty = mapOrSingleValue.addValue(value, multiplicity)\n if (isEmpty) {\n this.#inner.delete(key)\n }\n }\n }\n\n /**\n * Handle the transition from a single value to either a ValueMap or PrefixMap\n */\n #handleSingleValueTransition(\n key: TKey,\n currentSingleValue: SingleValue<TValue>,\n newValue: TValue,\n multiplicity: number\n ) {\n const [currentValue, currentMultiplicity] = currentSingleValue\n\n // Check for exact same value (reference equality)\n if (currentValue === newValue) {\n const newMultiplicity = currentMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.#inner.delete(key)\n } else {\n this.#inner.set(key, [newValue, newMultiplicity])\n }\n return\n }\n\n // Get prefixes for both values\n const newPrefix = getPrefix<TValue, TPrefix>(newValue)\n const currentPrefix = getPrefix<TValue, TPrefix>(currentValue)\n\n // Check if they're the same value by prefix/suffix comparison\n if (\n currentPrefix === newPrefix &&\n (currentValue === newValue || hash(currentValue) === hash(newValue))\n ) {\n const newMultiplicity = currentMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.#inner.delete(key)\n } else {\n this.#inner.set(key, [newValue, newMultiplicity])\n }\n return\n }\n\n // Different values - choose appropriate map type\n if (currentPrefix === NO_PREFIX && newPrefix === NO_PREFIX) {\n // Both have NO_PREFIX, use ValueMap directly\n const valueMap = new ValueMap<TValue>()\n valueMap.set(hash(currentValue), currentSingleValue)\n valueMap.set(hash(newValue), [newValue, multiplicity])\n this.#inner.set(key, valueMap)\n } else {\n // At least one has a prefix, use PrefixMap\n const prefixMap = new PrefixMap<TValue, TPrefix>()\n\n if (currentPrefix === newPrefix) {\n // Same prefix, different suffixes - need ValueMap within PrefixMap\n const valueMap = new ValueMap<TValue>()\n valueMap.set(hash(currentValue), currentSingleValue)\n valueMap.set(hash(newValue), [newValue, multiplicity])\n prefixMap.set(currentPrefix, valueMap)\n } else {\n // Different prefixes - store as separate single values\n prefixMap.set(currentPrefix, currentSingleValue)\n prefixMap.set(newPrefix, [newValue, multiplicity])\n }\n\n this.#inner.set(key, prefixMap)\n }\n }\n\n /**\n * This method appends another index to the current index.\n * @param other - The index to append to the current index.\n */\n append(other: Index<TKey, TValue>): void {\n for (const [key, value] of other.entries()) {\n this.addValue(key, value)\n }\n }\n\n /**\n * This method joins two indexes.\n * @param other - The index to join with the current index.\n * @returns A multiset of the joined values.\n */\n join<TValue2>(\n other: Index<TKey, TValue2>\n ): MultiSet<[TKey, [TValue, TValue2]]> {\n const result: Array<[[TKey, [TValue, TValue2]], number]> = []\n // We want to iterate over the smaller of the two indexes to reduce the\n // number of operations we need to do.\n if (this.size <= other.size) {\n for (const [key, valueIt] of this.entriesIterators()) {\n if (!other.has(key)) continue\n const otherValues = other.get(key)\n for (const [val1, mul1] of valueIt) {\n for (const [val2, mul2] of otherValues) {\n if (mul1 !== 0 && mul2 !== 0) {\n result.push([[key, [val1, val2]], mul1 * mul2])\n }\n }\n }\n }\n } else {\n for (const [key, otherValueIt] of other.entriesIterators()) {\n if (!this.has(key)) continue\n const values = this.get(key)\n for (const [val2, mul2] of otherValueIt) {\n for (const [val1, mul1] of values) {\n if (mul1 !== 0 && mul2 !== 0) {\n result.push([[key, [val1, val2]], mul1 * mul2])\n }\n }\n }\n }\n }\n\n return new MultiSet(result)\n }\n}\n\n/**\n * This function extracts the prefix from a value.\n * @param value - The value to extract the prefix from.\n * @returns The prefix and the suffix.\n */\nfunction getPrefix<TValue, TPrefix>(value: TValue): TPrefix | NO_PREFIX {\n // If the value is an array and the first element is a string or number, then the\n // first element is the prefix. This is used to distinguish between values without\n // the need for hashing unless there are multiple values for the same prefix.\n if (\n Array.isArray(value) &&\n (typeof value[0] === `string` ||\n typeof value[0] === `number` ||\n typeof value[0] === `bigint`)\n ) {\n return value[0] as TPrefix\n }\n return NO_PREFIX\n}\n\n/**\n * This function checks if a value is a single value.\n * @param value - The value to check.\n * @returns True if the value is a single value, false otherwise.\n */\nfunction isSingleValue<TValue>(\n value: SingleValue<TValue> | unknown\n): value is SingleValue<TValue> {\n return Array.isArray(value)\n}\n"],"names":["hash","MultiSet"],"mappings":";;;;;;;;;;;;;AAyCA,MAAM,YAAY,OAAO,WAAW;AAapC,MAAM,kBAAmC,IAGvC;AAAA;AAAA;AAAA;AAAA,EAIA,SAAS,OAAe,cAA+B;AACrD,QAAI,iBAAiB,EAAG,QAAO,KAAK,SAAS;AAE7C,UAAM,SAAS,UAA2B,KAAK;AAC/C,UAAM,wBAAwB,KAAK,IAAI,MAAM;AAE7C,QAAI,cAAc,qBAAqB,GAAG;AACxC,YAAM,CAAC,cAAc,mBAAmB,IAAI;AAC5C,YAAM,gBAAgB,UAA2B,YAAY;AAE7D,UAAI,kBAAkB,QAAQ;AAC5B,cAAM,IAAI,MAAM,gDAAgD;AAAA,MAClE;AAEA,UAAI,iBAAiB,SAASA,KAAAA,KAAK,YAAY,MAAMA,KAAAA,KAAK,KAAK,GAAG;AAEhE,cAAM,kBAAkB,sBAAsB;AAC9C,YAAI,oBAAoB,GAAG;AACzB,eAAK,OAAO,MAAM;AAAA,QACpB,OAAO;AACL,eAAK,IAAI,QAAQ,CAAC,OAAO,eAAe,CAAC;AAAA,QAC3C;AAAA,MACF,OAAO;AAEL,cAAM,WAAW,IAAI,SAAA;AACrB,iBAAS,IAAIA,KAAAA,KAAK,YAAY,GAAG,qBAAqB;AACtD,iBAAS,IAAIA,UAAK,KAAK,GAAG,CAAC,OAAO,YAAY,CAAC;AAC/C,aAAK,IAAI,QAAQ,QAAQ;AAAA,MAC3B;AAAA,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AAA,EACF;AAGA,MAAI,kBAAkB,aAAa,cAAc,WAAW;AAE1D,UAAM,WAAW,IAAI,SAAA;AACrB,aAAS,IAAIA,KAAAA,KAAK,YAAY,GAAG,kBAAkB;AACnD,aAAS,IAAIA,UAAK,QAAQ,GAAG,CAAC,UAAU,YAAY,CAAC;AACrD,uBAAK,QAAO,IAAI,KAAK,QAAQ;AAAA,EAC/B,OAAO;AAEL,UAAM,YAAY,IAAI,UAAA;AAEtB,QAAI,kBAAkB,WAAW;AAE/B,YAAM,WAAW,IAAI,SAAA;AACrB,eAAS,IAAIA,KAAAA,KAAK,YAAY,GAAG,kBAAkB;AACnD,eAAS,IAAIA,UAAK,QAAQ,GAAG,CAAC,UAAU,YAAY,CAAC;AACrD,gBAAU,IAAI,eAAe,QAAQ;AAAA,IACvC,OAAO;AAEL,gBAAU,IAAI,eAAe,kBAAkB;AAC/C,gBAAU,IAAI,WAAW,CAAC,UAAU,YAAY,CAAC;AAAA,IACnD;AAEA,uBAAK,QAAO,IAAI,KAAK,SAAS;AAAA,EAChC;AACF;AA0DF,SAAS,UAA2B,OAAoC;AAItE,MACE,MAAM,QAAQ,KAAK,MAClB,OAAO,MAAM,CAAC,MAAM,YACnB,OAAO,MAAM,CAAC,MAAM,YACpB,OAAO,MAAM,CAAC,MAAM,WACtB;AACA,WAAO,MAAM,CAAC;AAAA,EAChB;AACA,SAAO;AACT;AAOA,SAAS,cACP,OAC8B;AAC9B,SAAO,MAAM,QAAQ,KAAK;AAC5B;;"}
|
|
1
|
+
{"version":3,"file":"indexes.cjs","sources":["../../src/indexes.ts"],"sourcesContent":["/**\n * # Optimized Index Data Structure\n *\n * Multi-level index that adapts storage strategy based on data patterns to minimize memory\n * usage, eliminate wasteful lookups, and avoid hashing whenever possible.\n *\n * ## Storage Strategy\n *\n * **Single value**: `IndexMap['key'] → [value, multiplicity]` (no hashing needed)\n *\n * **Multiple unprefixed values**: Direct ValueMap (avoids NO_PREFIX lookup)\n * ```\n * IndexMap['key'] → ValueMap { hash(value1) → [value1, mult1], ... }\n * ```\n *\n * **Values with prefixes**: PrefixMap uses prefix keys directly (no hashing)\n * ```\n * IndexMap['key'] → PrefixMap { 'prefix1' → [value1, mult1], NO_PREFIX → ValueMap{...} }\n * ```\n *\n * **Multiple values per prefix**: ValueMap within PrefixMap (hash only suffixes)\n * ```\n * PrefixMap['prefix'] → ValueMap { hash(suffix1) → [full_value1, mult1], ... }\n * ```\n *\n * ## Dynamic Evolution\n *\n * Structure automatically evolves as data is added:\n * - Single → ValueMap (when both values unprefixed)\n * - Single → PrefixMap (when at least one prefixed)\n * - ValueMap → PrefixMap (adding prefixed value to unprefixed)\n *\n * Prefixes extracted from array values: `['prefix', 'suffix']` → prefix='prefix'\n */\n\nimport { MultiSet } from \"./multiset.js\"\nimport { hash } from \"./hashing/index.js\"\nimport type { Hash } from \"./hashing/index.js\"\n\n// We use a symbol to represent the absence of a prefix, unprefixed values a stored\n// against this key.\nconst NO_PREFIX = Symbol(`NO_PREFIX`)\ntype NO_PREFIX = typeof NO_PREFIX\n\n// A single value is a tuple of the value and the multiplicity.\ntype SingleValue<TValue> = [TValue, number]\n\n// Base map type for the index. Stores single values, prefix maps, or value maps against a key.\ntype IndexMap<TKey, TValue, TPrefix> = Map<\n TKey,\n SingleValue<TValue> | PrefixMap<TValue, TPrefix> | ValueMap<TValue>\n>\n\n// Second level map type for the index, stores single values or value maps against a prefix.\nclass PrefixMap<TValue, TPrefix> extends Map<\n TPrefix | NO_PREFIX,\n SingleValue<TValue> | ValueMap<TValue>\n> {\n /**\n * Add a value to the PrefixMap. Returns true if the map becomes empty after the operation.\n */\n addValue(value: TValue, multiplicity: number): boolean {\n if (multiplicity === 0) return this.size === 0\n\n const prefix = getPrefix<TValue, TPrefix>(value)\n const valueMapOrSingleValue = this.get(prefix)\n\n if (isSingleValue(valueMapOrSingleValue)) {\n const [currentValue, currentMultiplicity] = valueMapOrSingleValue\n const currentPrefix = getPrefix<TValue, TPrefix>(currentValue)\n\n if (currentPrefix !== prefix) {\n throw new Error(`Mismatching prefixes, this should never happen`)\n }\n\n if (currentValue === value || hash(currentValue) === hash(value)) {\n // Same value, update multiplicity\n const newMultiplicity = currentMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.delete(prefix)\n } else {\n this.set(prefix, [value, newMultiplicity])\n }\n } else {\n // Different suffixes, need to create ValueMap\n const valueMap = new ValueMap<TValue>()\n valueMap.set(hash(currentValue), valueMapOrSingleValue)\n valueMap.set(hash(value), [value, multiplicity])\n this.set(prefix, valueMap)\n }\n } else if (valueMapOrSingleValue === undefined) {\n // No existing value for this prefix\n this.set(prefix, [value, multiplicity])\n } else {\n // Existing ValueMap\n const isEmpty = valueMapOrSingleValue.addValue(value, multiplicity)\n if (isEmpty) {\n this.delete(prefix)\n }\n }\n\n return this.size === 0\n }\n}\n\n// Third level map type for the index, stores single values or value maps against a hash.\nclass ValueMap<TValue> extends Map<Hash, [TValue, number]> {\n /**\n * Add a value to the ValueMap. Returns true if the map becomes empty after the operation.\n * @param value - The full value to store\n * @param multiplicity - The multiplicity to add\n * @param hashKey - Optional hash key to use instead of hashing the full value (used when in PrefixMap context)\n */\n addValue(value: TValue, multiplicity: number): boolean {\n if (multiplicity === 0) return this.size === 0\n\n const key = hash(value)\n const currentValue = this.get(key)\n\n if (currentValue) {\n const [, currentMultiplicity] = currentValue\n const newMultiplicity = currentMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.delete(key)\n } else {\n this.set(key, [value, newMultiplicity])\n }\n } else {\n this.set(key, [value, multiplicity])\n }\n\n return this.size === 0\n }\n}\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 Index<TKey, TValue, TPrefix = any> {\n /*\n * This index maintains a nested map of keys -> (value, multiplicities), where:\n * - initially the values are stored against the key as a single value tuple\n * - when a key gets additional values, the values are stored against the key in a\n * prefix map\n * - the prefix is extract where possible from values that are structured as\n * [rowPrimaryKey, rowValue], as they are in the Tanstack DB query pipeline.\n * - only when there are multiple values for a given prefix do we fall back to a\n * hash to identify identical values, storing them in a third level value map.\n */\n #inner: IndexMap<TKey, TValue, TPrefix>\n #consolidatedMultiplicity: Map<TKey, number> = new Map() // sum of multiplicities per key\n\n constructor() {\n this.#inner = new Map()\n }\n\n /**\n * Create an Index from multiple MultiSet messages.\n * @param messages - Array of MultiSet messages to build the index from.\n * @returns A new Index containing all the data from the messages.\n */\n static fromMultiSets<K, V>(messages: Array<MultiSet<[K, V]>>): Index<K, V> {\n const index = new Index<K, V>()\n\n for (const message of messages) {\n for (const [item, multiplicity] of message.getInner()) {\n const [key, value] = item\n index.addValue(key, [value, multiplicity])\n }\n }\n\n return index\n }\n\n /**\n * This method returns a string representation of the index.\n * @param indent - Whether to indent the string representation.\n * @returns A string representation of the index.\n */\n toString(indent = false): string {\n return `Index(${JSON.stringify(\n [...this.entries()],\n undefined,\n indent ? 2 : undefined\n )})`\n }\n\n /**\n * The size of the index.\n */\n get size(): number {\n return this.#inner.size\n }\n\n /**\n * This method checks if the index has a given key.\n * @param key - The key to check.\n * @returns True if the index has the key, false otherwise.\n */\n has(key: TKey): boolean {\n return this.#inner.has(key)\n }\n\n /**\n * Check if a key has presence (non-zero consolidated multiplicity).\n * @param key - The key to check.\n * @returns True if the key has non-zero consolidated multiplicity, false otherwise.\n */\n hasPresence(key: TKey): boolean {\n return (this.#consolidatedMultiplicity.get(key) || 0) !== 0\n }\n\n /**\n * Get the consolidated multiplicity (sum of multiplicities) for a key.\n * @param key - The key to get the consolidated multiplicity for.\n * @returns The consolidated multiplicity for the key.\n */\n getConsolidatedMultiplicity(key: TKey): number {\n return this.#consolidatedMultiplicity.get(key) || 0\n }\n\n /**\n * Get all keys that have presence (non-zero consolidated multiplicity).\n * @returns An iterator of keys with non-zero consolidated multiplicity.\n */\n getPresenceKeys(): Iterable<TKey> {\n return this.#consolidatedMultiplicity.keys()\n }\n\n /**\n * This method returns all values for a given key.\n * @param key - The key to get the values for.\n * @returns An array of value tuples [value, multiplicity].\n */\n get(key: TKey): Array<[TValue, number]> {\n return [...this.getIterator(key)]\n }\n\n /**\n * This method returns an iterator over all values for a given key.\n * @param key - The key to get the values for.\n * @returns An iterator of value tuples [value, multiplicity].\n */\n *getIterator(key: TKey): Iterable<[TValue, number]> {\n const mapOrSingleValue = this.#inner.get(key)\n if (isSingleValue(mapOrSingleValue)) {\n yield mapOrSingleValue\n } else if (mapOrSingleValue === undefined) {\n return\n } else if (mapOrSingleValue instanceof ValueMap) {\n // Direct ValueMap - all values have NO_PREFIX\n for (const valueTuple of mapOrSingleValue.values()) {\n yield valueTuple\n }\n } else {\n // PrefixMap - iterate through all prefixes\n for (const singleValueOrValueMap of mapOrSingleValue.values()) {\n if (isSingleValue(singleValueOrValueMap)) {\n yield singleValueOrValueMap\n } else {\n for (const valueTuple of singleValueOrValueMap.values()) {\n yield valueTuple\n }\n }\n }\n }\n }\n\n /**\n * This returns an iterator that iterates over all key-value pairs.\n * @returns An iterable of all key-value pairs (and their multiplicities) in the index.\n */\n *entries(): Iterable<[TKey, [TValue, number]]> {\n for (const key of this.#inner.keys()) {\n for (const valueTuple of this.getIterator(key)) {\n yield [key, valueTuple]\n }\n }\n }\n\n /**\n * This method only iterates over the keys and not over the values.\n * Hence, it is more efficient than the `#entries` method.\n * It returns an iterator that you can use if you need to iterate over the values for a given key.\n * @returns An iterator of all *keys* in the index and their corresponding value iterator.\n */\n *entriesIterators(): Iterable<[TKey, Iterable<[TValue, number]>]> {\n for (const key of this.#inner.keys()) {\n yield [key, this.getIterator(key)]\n }\n }\n\n /**\n * This method adds a value to the index.\n * @param key - The key to add the value to.\n * @param valueTuple - The value tuple [value, multiplicity] to add to the index.\n */\n addValue(key: TKey, valueTuple: SingleValue<TValue>) {\n const [value, multiplicity] = valueTuple\n // If the multiplicity is 0, do nothing\n if (multiplicity === 0) return\n\n // Update consolidated multiplicity tracking\n const newConsolidatedMultiplicity =\n (this.#consolidatedMultiplicity.get(key) || 0) + multiplicity\n if (newConsolidatedMultiplicity === 0) {\n this.#consolidatedMultiplicity.delete(key)\n } else {\n this.#consolidatedMultiplicity.set(key, newConsolidatedMultiplicity)\n }\n\n const mapOrSingleValue = this.#inner.get(key)\n\n if (mapOrSingleValue === undefined) {\n // First value for this key\n this.#inner.set(key, valueTuple)\n return\n }\n\n if (isSingleValue(mapOrSingleValue)) {\n // Handle transition from single value to map\n this.#handleSingleValueTransition(\n key,\n mapOrSingleValue,\n value,\n multiplicity\n )\n return\n }\n\n if (mapOrSingleValue instanceof ValueMap) {\n // Handle existing ValueMap\n const prefix = getPrefix<TValue, TPrefix>(value)\n if (prefix !== NO_PREFIX) {\n // Convert ValueMap to PrefixMap since we have a prefixed value\n const prefixMap = new PrefixMap<TValue, TPrefix>()\n prefixMap.set(NO_PREFIX, mapOrSingleValue)\n prefixMap.set(prefix, valueTuple)\n this.#inner.set(key, prefixMap)\n } else {\n // Add to existing ValueMap\n const isEmpty = mapOrSingleValue.addValue(value, multiplicity)\n if (isEmpty) {\n this.#inner.delete(key)\n }\n }\n } else {\n // Handle existing PrefixMap\n const isEmpty = mapOrSingleValue.addValue(value, multiplicity)\n if (isEmpty) {\n this.#inner.delete(key)\n }\n }\n }\n\n /**\n * Handle the transition from a single value to either a ValueMap or PrefixMap\n */\n #handleSingleValueTransition(\n key: TKey,\n currentSingleValue: SingleValue<TValue>,\n newValue: TValue,\n multiplicity: number\n ) {\n const [currentValue, currentMultiplicity] = currentSingleValue\n\n // Check for exact same value (reference equality)\n if (currentValue === newValue) {\n const newMultiplicity = currentMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.#inner.delete(key)\n } else {\n this.#inner.set(key, [newValue, newMultiplicity])\n }\n return\n }\n\n // Get prefixes for both values\n const newPrefix = getPrefix<TValue, TPrefix>(newValue)\n const currentPrefix = getPrefix<TValue, TPrefix>(currentValue)\n\n // Check if they're the same value by prefix/suffix comparison\n if (\n currentPrefix === newPrefix &&\n (currentValue === newValue || hash(currentValue) === hash(newValue))\n ) {\n const newMultiplicity = currentMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.#inner.delete(key)\n } else {\n this.#inner.set(key, [newValue, newMultiplicity])\n }\n return\n }\n\n // Different values - choose appropriate map type\n if (currentPrefix === NO_PREFIX && newPrefix === NO_PREFIX) {\n // Both have NO_PREFIX, use ValueMap directly\n const valueMap = new ValueMap<TValue>()\n valueMap.set(hash(currentValue), currentSingleValue)\n valueMap.set(hash(newValue), [newValue, multiplicity])\n this.#inner.set(key, valueMap)\n } else {\n // At least one has a prefix, use PrefixMap\n const prefixMap = new PrefixMap<TValue, TPrefix>()\n\n if (currentPrefix === newPrefix) {\n // Same prefix, different suffixes - need ValueMap within PrefixMap\n const valueMap = new ValueMap<TValue>()\n valueMap.set(hash(currentValue), currentSingleValue)\n valueMap.set(hash(newValue), [newValue, multiplicity])\n prefixMap.set(currentPrefix, valueMap)\n } else {\n // Different prefixes - store as separate single values\n prefixMap.set(currentPrefix, currentSingleValue)\n prefixMap.set(newPrefix, [newValue, multiplicity])\n }\n\n this.#inner.set(key, prefixMap)\n }\n }\n\n /**\n * This method appends another index to the current index.\n * @param other - The index to append to the current index.\n */\n append(other: Index<TKey, TValue>): void {\n for (const [key, value] of other.entries()) {\n this.addValue(key, value)\n }\n }\n\n /**\n * This method joins two indexes.\n * @param other - The index to join with the current index.\n * @returns A multiset of the joined values.\n */\n join<TValue2>(\n other: Index<TKey, TValue2>\n ): MultiSet<[TKey, [TValue, TValue2]]> {\n const result: Array<[[TKey, [TValue, TValue2]], number]> = []\n // We want to iterate over the smaller of the two indexes to reduce the\n // number of operations we need to do.\n if (this.size <= other.size) {\n for (const [key, valueIt] of this.entriesIterators()) {\n if (!other.has(key)) continue\n const otherValues = other.get(key)\n for (const [val1, mul1] of valueIt) {\n for (const [val2, mul2] of otherValues) {\n if (mul1 !== 0 && mul2 !== 0) {\n result.push([[key, [val1, val2]], mul1 * mul2])\n }\n }\n }\n }\n } else {\n for (const [key, otherValueIt] of other.entriesIterators()) {\n if (!this.has(key)) continue\n const values = this.get(key)\n for (const [val2, mul2] of otherValueIt) {\n for (const [val1, mul1] of values) {\n if (mul1 !== 0 && mul2 !== 0) {\n result.push([[key, [val1, val2]], mul1 * mul2])\n }\n }\n }\n }\n }\n\n return new MultiSet(result)\n }\n}\n\n/**\n * This function extracts the prefix from a value.\n * @param value - The value to extract the prefix from.\n * @returns The prefix and the suffix.\n */\nfunction getPrefix<TValue, TPrefix>(value: TValue): TPrefix | NO_PREFIX {\n // If the value is an array and the first element is a string or number, then the\n // first element is the prefix. This is used to distinguish between values without\n // the need for hashing unless there are multiple values for the same prefix.\n if (\n Array.isArray(value) &&\n (typeof value[0] === `string` ||\n typeof value[0] === `number` ||\n typeof value[0] === `bigint`)\n ) {\n return value[0] as TPrefix\n }\n return NO_PREFIX\n}\n\n/**\n * This function checks if a value is a single value.\n * @param value - The value to check.\n * @returns True if the value is a single value, false otherwise.\n */\nfunction isSingleValue<TValue>(\n value: SingleValue<TValue> | unknown\n): value is SingleValue<TValue> {\n return Array.isArray(value)\n}\n"],"names":["hash","MultiSet"],"mappings":";;;;AAyCA,MAAM,YAAY,OAAO,WAAW;AAapC,MAAM,kBAAmC,IAGvC;AAAA;AAAA;AAAA;AAAA,EAIA,SAAS,OAAe,cAA+B;AACrD,QAAI,iBAAiB,EAAG,QAAO,KAAK,SAAS;AAE7C,UAAM,SAAS,UAA2B,KAAK;AAC/C,UAAM,wBAAwB,KAAK,IAAI,MAAM;AAE7C,QAAI,cAAc,qBAAqB,GAAG;AACxC,YAAM,CAAC,cAAc,mBAAmB,IAAI;AAC5C,YAAM,gBAAgB,UAA2B,YAAY;AAE7D,UAAI,kBAAkB,QAAQ;AAC5B,cAAM,IAAI,MAAM,gDAAgD;AAAA,MAClE;AAEA,UAAI,iBAAiB,SAASA,KAAAA,KAAK,YAAY,MAAMA,KAAAA,KAAK,KAAK,GAAG;AAEhE,cAAM,kBAAkB,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,SAAS,KAAK,SAAS,GAAG;AAC5B,qBAAO,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,IAAI,CAAC,GAAG,OAAO,IAAI,CAAC;AAAA,YAChD;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,OAAO;AACL,iBAAW,CAAC,KAAK,YAAY,KAAK,MAAM,oBAAoB;AAC1D,YAAI,CAAC,KAAK,IAAI,GAAG,EAAG;AACpB,cAAM,SAAS,KAAK,IAAI,GAAG;AAC3B,mBAAW,CAAC,MAAM,IAAI,KAAK,cAAc;AACvC,qBAAW,CAAC,MAAM,IAAI,KAAK,QAAQ;AACjC,gBAAI,SAAS,KAAK,SAAS,GAAG;AAC5B,qBAAO,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,IAAI,CAAC,GAAG,OAAO,IAAI,CAAC;AAAA,YAChD;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,WAAO,IAAIC,SAAAA,SAAS,MAAM;AAAA,EAC5B;AACF;AAOA,SAAS,UAA2B,OAAoC;AAItE,MACE,MAAM,QAAQ,KAAK,MAClB,OAAO,MAAM,CAAC,MAAM,YACnB,OAAO,MAAM,CAAC,MAAM,YACpB,OAAO,MAAM,CAAC,MAAM,WACtB;AACA,WAAO,MAAM,CAAC;AAAA,EAChB;AACA,SAAO;AACT;AAOA,SAAS,cACP,OAC8B;AAC9B,SAAO,MAAM,QAAQ,KAAK;AAC5B;;"}
|
package/dist/cjs/indexes.d.cts
CHANGED
|
@@ -8,6 +8,12 @@ type SingleValue<TValue> = [TValue, number];
|
|
|
8
8
|
export declare class Index<TKey, TValue, TPrefix = any> {
|
|
9
9
|
#private;
|
|
10
10
|
constructor();
|
|
11
|
+
/**
|
|
12
|
+
* Create an Index from multiple MultiSet messages.
|
|
13
|
+
* @param messages - Array of MultiSet messages to build the index from.
|
|
14
|
+
* @returns A new Index containing all the data from the messages.
|
|
15
|
+
*/
|
|
16
|
+
static fromMultiSets<K, V>(messages: Array<MultiSet<[K, V]>>): Index<K, V>;
|
|
11
17
|
/**
|
|
12
18
|
* This method returns a string representation of the index.
|
|
13
19
|
* @param indent - Whether to indent the string representation.
|
|
@@ -24,6 +30,23 @@ export declare class Index<TKey, TValue, TPrefix = any> {
|
|
|
24
30
|
* @returns True if the index has the key, false otherwise.
|
|
25
31
|
*/
|
|
26
32
|
has(key: TKey): boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Check if a key has presence (non-zero consolidated multiplicity).
|
|
35
|
+
* @param key - The key to check.
|
|
36
|
+
* @returns True if the key has non-zero consolidated multiplicity, false otherwise.
|
|
37
|
+
*/
|
|
38
|
+
hasPresence(key: TKey): boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Get the consolidated multiplicity (sum of multiplicities) for a key.
|
|
41
|
+
* @param key - The key to get the consolidated multiplicity for.
|
|
42
|
+
* @returns The consolidated multiplicity for the key.
|
|
43
|
+
*/
|
|
44
|
+
getConsolidatedMultiplicity(key: TKey): number;
|
|
45
|
+
/**
|
|
46
|
+
* Get all keys that have presence (non-zero consolidated multiplicity).
|
|
47
|
+
* @returns An iterator of keys with non-zero consolidated multiplicity.
|
|
48
|
+
*/
|
|
49
|
+
getPresenceKeys(): Iterable<TKey>;
|
|
27
50
|
/**
|
|
28
51
|
* This method returns all values for a given key.
|
|
29
52
|
* @param key - The key to get the values for.
|
package/dist/cjs/multiset.cjs
CHANGED
|
@@ -1,51 +1,41 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __typeError = (msg) => {
|
|
3
|
-
throw TypeError(msg);
|
|
4
|
-
};
|
|
5
|
-
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
6
|
-
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
7
|
-
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
8
|
-
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
9
|
-
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
10
|
-
var _inner, _MultiSet_instances, consolidateKeyed_fn, consolidateUnkeyed_fn;
|
|
11
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
12
3
|
const utils = require("./utils.cjs");
|
|
13
4
|
const hash = require("./hashing/hash.cjs");
|
|
14
|
-
|
|
5
|
+
class MultiSet {
|
|
6
|
+
#inner;
|
|
15
7
|
constructor(data = []) {
|
|
16
|
-
|
|
17
|
-
__privateAdd(this, _inner);
|
|
18
|
-
__privateSet(this, _inner, data);
|
|
8
|
+
this.#inner = data;
|
|
19
9
|
}
|
|
20
10
|
toString(indent = false) {
|
|
21
|
-
return `MultiSet(${JSON.stringify(
|
|
11
|
+
return `MultiSet(${JSON.stringify(this.#inner, null, indent ? 2 : void 0)})`;
|
|
22
12
|
}
|
|
23
13
|
toJSON() {
|
|
24
14
|
return JSON.stringify(Array.from(this.getInner()));
|
|
25
15
|
}
|
|
26
16
|
static fromJSON(json) {
|
|
27
|
-
return new
|
|
17
|
+
return new MultiSet(JSON.parse(json));
|
|
28
18
|
}
|
|
29
19
|
/**
|
|
30
20
|
* Apply a function to all records in the collection.
|
|
31
21
|
*/
|
|
32
22
|
map(f) {
|
|
33
|
-
return new
|
|
34
|
-
|
|
23
|
+
return new MultiSet(
|
|
24
|
+
this.#inner.map(([data, multiplicity]) => [f(data), multiplicity])
|
|
35
25
|
);
|
|
36
26
|
}
|
|
37
27
|
/**
|
|
38
28
|
* Filter out records for which a function f(record) evaluates to False.
|
|
39
29
|
*/
|
|
40
30
|
filter(f) {
|
|
41
|
-
return new
|
|
31
|
+
return new MultiSet(this.#inner.filter(([data, _]) => f(data)));
|
|
42
32
|
}
|
|
43
33
|
/**
|
|
44
34
|
* Negate all multiplicities in the collection.
|
|
45
35
|
*/
|
|
46
36
|
negate() {
|
|
47
|
-
return new
|
|
48
|
-
|
|
37
|
+
return new MultiSet(
|
|
38
|
+
this.#inner.map(([data, multiplicity]) => [data, -multiplicity])
|
|
49
39
|
);
|
|
50
40
|
}
|
|
51
41
|
/**
|
|
@@ -53,9 +43,9 @@ const _MultiSet = class _MultiSet {
|
|
|
53
43
|
*/
|
|
54
44
|
concat(other) {
|
|
55
45
|
const out = [];
|
|
56
|
-
utils.chunkedArrayPush(out,
|
|
46
|
+
utils.chunkedArrayPush(out, this.#inner);
|
|
57
47
|
utils.chunkedArrayPush(out, other.getInner());
|
|
58
|
-
return new
|
|
48
|
+
return new MultiSet(out);
|
|
59
49
|
}
|
|
60
50
|
/**
|
|
61
51
|
* Produce as output a collection that is logically equivalent to the input
|
|
@@ -63,112 +53,113 @@ const _MultiSet = class _MultiSet {
|
|
|
63
53
|
* (record, multiplicity) pair.
|
|
64
54
|
*/
|
|
65
55
|
consolidate() {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const firstItem = (_a = __privateGet(this, _inner)[0]) == null ? void 0 : _a[0];
|
|
56
|
+
if (this.#inner.length > 0) {
|
|
57
|
+
const firstItem = this.#inner[0]?.[0];
|
|
69
58
|
if (Array.isArray(firstItem) && firstItem.length === 2) {
|
|
70
|
-
return
|
|
59
|
+
return this.#consolidateKeyed();
|
|
71
60
|
}
|
|
72
61
|
}
|
|
73
|
-
return
|
|
62
|
+
return this.#consolidateUnkeyed();
|
|
74
63
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
valueId = utils.globalObjectIdGenerator.getStringId(value);
|
|
64
|
+
/**
|
|
65
|
+
* Private method for consolidating keyed multisets where keys are strings/numbers
|
|
66
|
+
* and values are compared by reference equality.
|
|
67
|
+
*
|
|
68
|
+
* This method provides significant performance improvements over the hash-based approach
|
|
69
|
+
* by using WeakMap for object reference tracking and avoiding expensive serialization.
|
|
70
|
+
*
|
|
71
|
+
* Special handling for join operations: When values are tuples of length 2 (common in joins),
|
|
72
|
+
* we unpack them and compare each element individually to maintain proper equality semantics.
|
|
73
|
+
*/
|
|
74
|
+
#consolidateKeyed() {
|
|
75
|
+
const consolidated = /* @__PURE__ */ new Map();
|
|
76
|
+
const values = /* @__PURE__ */ new Map();
|
|
77
|
+
const getTupleId = (tuple) => {
|
|
78
|
+
if (tuple.length !== 2) {
|
|
79
|
+
throw new Error(`Expected tuple of length 2`);
|
|
80
|
+
}
|
|
81
|
+
const [first, second] = tuple;
|
|
82
|
+
return `${utils.globalObjectIdGenerator.getStringId(first)}|${utils.globalObjectIdGenerator.getStringId(second)}`;
|
|
83
|
+
};
|
|
84
|
+
for (const [data, multiplicity] of this.#inner) {
|
|
85
|
+
if (!Array.isArray(data) || data.length !== 2) {
|
|
86
|
+
return this.#consolidateUnkeyed();
|
|
87
|
+
}
|
|
88
|
+
const [key, value] = data;
|
|
89
|
+
if (typeof key !== `string` && typeof key !== `number`) {
|
|
90
|
+
return this.#consolidateUnkeyed();
|
|
91
|
+
}
|
|
92
|
+
let valueId;
|
|
93
|
+
if (Array.isArray(value) && value.length === 2) {
|
|
94
|
+
valueId = getTupleId(value);
|
|
95
|
+
} else {
|
|
96
|
+
valueId = utils.globalObjectIdGenerator.getStringId(value);
|
|
97
|
+
}
|
|
98
|
+
const compositeKey = key + `|` + valueId;
|
|
99
|
+
consolidated.set(
|
|
100
|
+
compositeKey,
|
|
101
|
+
(consolidated.get(compositeKey) || 0) + multiplicity
|
|
102
|
+
);
|
|
103
|
+
if (!values.has(compositeKey)) {
|
|
104
|
+
values.set(compositeKey, data);
|
|
105
|
+
}
|
|
118
106
|
}
|
|
119
|
-
const
|
|
120
|
-
consolidated
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
if (!values.has(compositeKey)) {
|
|
125
|
-
values.set(compositeKey, data);
|
|
107
|
+
const result = [];
|
|
108
|
+
for (const [compositeKey, multiplicity] of consolidated) {
|
|
109
|
+
if (multiplicity !== 0) {
|
|
110
|
+
result.push([values.get(compositeKey), multiplicity]);
|
|
111
|
+
}
|
|
126
112
|
}
|
|
113
|
+
return new MultiSet(result);
|
|
127
114
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
115
|
+
/**
|
|
116
|
+
* Private method for consolidating unkeyed multisets using the original approach.
|
|
117
|
+
*/
|
|
118
|
+
#consolidateUnkeyed() {
|
|
119
|
+
const consolidated = new utils.DefaultMap(() => 0);
|
|
120
|
+
const values = /* @__PURE__ */ new Map();
|
|
121
|
+
let hasString = false;
|
|
122
|
+
let hasNumber = false;
|
|
123
|
+
let hasOther = false;
|
|
124
|
+
for (const [data, _] of this.#inner) {
|
|
125
|
+
if (typeof data === `string`) {
|
|
126
|
+
hasString = true;
|
|
127
|
+
} else if (typeof data === `number`) {
|
|
128
|
+
hasNumber = true;
|
|
129
|
+
} else {
|
|
130
|
+
hasOther = true;
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
132
133
|
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const consolidated = new utils.DefaultMap(() => 0);
|
|
141
|
-
const values = /* @__PURE__ */ new Map();
|
|
142
|
-
let hasString = false;
|
|
143
|
-
let hasNumber = false;
|
|
144
|
-
let hasOther = false;
|
|
145
|
-
for (const [data, _] of __privateGet(this, _inner)) {
|
|
146
|
-
if (typeof data === `string`) {
|
|
147
|
-
hasString = true;
|
|
148
|
-
} else if (typeof data === `number`) {
|
|
149
|
-
hasNumber = true;
|
|
150
|
-
} else {
|
|
151
|
-
hasOther = true;
|
|
152
|
-
break;
|
|
134
|
+
const requireJson = hasOther || hasString && hasNumber;
|
|
135
|
+
for (const [data, multiplicity] of this.#inner) {
|
|
136
|
+
const key = requireJson ? hash.hash(data) : data;
|
|
137
|
+
if (requireJson && !values.has(key)) {
|
|
138
|
+
values.set(key, data);
|
|
139
|
+
}
|
|
140
|
+
consolidated.update(key, (count) => count + multiplicity);
|
|
153
141
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
142
|
+
const result = [];
|
|
143
|
+
for (const [key, multiplicity] of consolidated.entries()) {
|
|
144
|
+
if (multiplicity !== 0) {
|
|
145
|
+
const parsedKey = requireJson ? values.get(key) : key;
|
|
146
|
+
result.push([parsedKey, multiplicity]);
|
|
147
|
+
}
|
|
160
148
|
}
|
|
161
|
-
|
|
149
|
+
return new MultiSet(result);
|
|
162
150
|
}
|
|
163
|
-
|
|
164
|
-
|
|
151
|
+
extend(other) {
|
|
152
|
+
const otherArray = other instanceof MultiSet ? other.getInner() : other;
|
|
153
|
+
utils.chunkedArrayPush(this.#inner, otherArray);
|
|
154
|
+
}
|
|
155
|
+
add(item, multiplicity) {
|
|
165
156
|
if (multiplicity !== 0) {
|
|
166
|
-
|
|
167
|
-
result.push([parsedKey, multiplicity]);
|
|
157
|
+
this.#inner.push([item, multiplicity]);
|
|
168
158
|
}
|
|
169
159
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
160
|
+
getInner() {
|
|
161
|
+
return this.#inner;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
173
164
|
exports.MultiSet = MultiSet;
|
|
174
165
|
//# sourceMappingURL=multiset.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multiset.cjs","sources":["../../src/multiset.ts"],"sourcesContent":["import {\n DefaultMap,\n chunkedArrayPush,\n globalObjectIdGenerator,\n} from \"./utils.js\"\nimport { hash } from \"./hashing/index.js\"\n\nexport type MultiSetArray<T> = Array<[T, number]>\nexport type KeyedData<T> = [key: string, value: T]\n\n/**\n * A multiset of data.\n */\nexport class MultiSet<T> {\n #inner: MultiSetArray<T>\n\n constructor(data: MultiSetArray<T> = []) {\n this.#inner = data\n }\n\n toString(indent = false): string {\n return `MultiSet(${JSON.stringify(this.#inner, null, indent ? 2 : undefined)})`\n }\n\n toJSON(): string {\n return JSON.stringify(Array.from(this.getInner()))\n }\n\n static fromJSON<U>(json: string): MultiSet<U> {\n return new MultiSet(JSON.parse(json))\n }\n\n /**\n * Apply a function to all records in the collection.\n */\n map<U>(f: (data: T) => U): MultiSet<U> {\n return new MultiSet(\n this.#inner.map(([data, multiplicity]) => [f(data), multiplicity])\n )\n }\n\n /**\n * Filter out records for which a function f(record) evaluates to False.\n */\n filter(f: (data: T) => boolean): MultiSet<T> {\n return new MultiSet(this.#inner.filter(([data, _]) => f(data)))\n }\n\n /**\n * Negate all multiplicities in the collection.\n */\n negate(): MultiSet<T> {\n return new MultiSet(\n this.#inner.map(([data, multiplicity]) => [data, -multiplicity])\n )\n }\n\n /**\n * Concatenate two collections together.\n */\n concat(other: MultiSet<T>): MultiSet<T> {\n const out: MultiSetArray<T> = []\n chunkedArrayPush(out, this.#inner)\n chunkedArrayPush(out, other.getInner())\n return new MultiSet(out)\n }\n\n /**\n * Produce as output a collection that is logically equivalent to the input\n * but which combines identical instances of the same record into one\n * (record, multiplicity) pair.\n */\n consolidate(): MultiSet<T> {\n // Check if this looks like a keyed multiset (first item is a tuple of length 2)\n if (this.#inner.length > 0) {\n const firstItem = this.#inner[0]?.[0]\n if (Array.isArray(firstItem) && firstItem.length === 2) {\n return this.#consolidateKeyed()\n }\n }\n\n // Fall back to original method for unkeyed data\n return this.#consolidateUnkeyed()\n }\n\n /**\n * Private method for consolidating keyed multisets where keys are strings/numbers\n * and values are compared by reference equality.\n *\n * This method provides significant performance improvements over the hash-based approach\n * by using WeakMap for object reference tracking and avoiding expensive serialization.\n *\n * Special handling for join operations: When values are tuples of length 2 (common in joins),\n * we unpack them and compare each element individually to maintain proper equality semantics.\n */\n #consolidateKeyed(): MultiSet<T> {\n const consolidated = new Map<string, number>()\n const values = new Map<string, T>()\n\n // Use global object ID generator for consistent reference equality\n\n /**\n * Special handler for tuples (arrays of length 2) commonly produced by join operations.\n * Unpacks the tuple and generates an ID based on both elements to ensure proper\n * consolidation of join results like ['A', null] and [null, 'X'].\n */\n const getTupleId = (tuple: Array<any>): string => {\n if (tuple.length !== 2) {\n throw new Error(`Expected tuple of length 2`)\n }\n const [first, second] = tuple\n return `${globalObjectIdGenerator.getStringId(first)}|${globalObjectIdGenerator.getStringId(second)}`\n }\n\n // Process each item in the multiset\n for (const [data, multiplicity] of this.#inner) {\n // Verify this is still a keyed item (should be [key, value] pair)\n if (!Array.isArray(data) || data.length !== 2) {\n // Found non-keyed item, fall back to unkeyed consolidation\n return this.#consolidateUnkeyed()\n }\n\n const [key, value] = data\n\n // Verify key is string or number as expected for keyed multisets\n if (typeof key !== `string` && typeof key !== `number`) {\n // Found non-string/number key, fall back to unkeyed consolidation\n return this.#consolidateUnkeyed()\n }\n\n // Generate value ID with special handling for join tuples\n let valueId: string\n if (Array.isArray(value) && value.length === 2) {\n // Special case: value is a tuple from join operations\n valueId = getTupleId(value)\n } else {\n // Regular case: use reference/value equality\n valueId = globalObjectIdGenerator.getStringId(value)\n }\n\n // Create composite key and consolidate\n const compositeKey = key + `|` + valueId\n consolidated.set(\n compositeKey,\n (consolidated.get(compositeKey) || 0) + multiplicity\n )\n\n // Store the original data for the first occurrence\n if (!values.has(compositeKey)) {\n values.set(compositeKey, data as T)\n }\n }\n\n // Build result array, filtering out zero multiplicities\n const result: MultiSetArray<T> = []\n for (const [compositeKey, multiplicity] of consolidated) {\n if (multiplicity !== 0) {\n result.push([values.get(compositeKey)!, multiplicity])\n }\n }\n\n return new MultiSet(result)\n }\n\n /**\n * Private method for consolidating unkeyed multisets using the original approach.\n */\n #consolidateUnkeyed(): MultiSet<T> {\n const consolidated = new DefaultMap<string | number, number>(() => 0)\n const values = new Map<string, any>()\n\n let hasString = false\n let hasNumber = false\n let hasOther = false\n for (const [data, _] of this.#inner) {\n if (typeof data === `string`) {\n hasString = true\n } else if (typeof data === `number`) {\n hasNumber = true\n } else {\n hasOther = true\n break\n }\n }\n\n const requireJson = hasOther || (hasString && hasNumber)\n\n for (const [data, multiplicity] of this.#inner) {\n const key = requireJson ? hash(data) : (data as string | number)\n if (requireJson && !values.has(key as string)) {\n values.set(key as string, data)\n }\n consolidated.update(key, (count) => count + multiplicity)\n }\n\n const result: MultiSetArray<T> = []\n for (const [key, multiplicity] of consolidated.entries()) {\n if (multiplicity !== 0) {\n const parsedKey = requireJson ? values.get(key as string) : key\n result.push([parsedKey as T, multiplicity])\n }\n }\n\n return new MultiSet(result)\n }\n\n extend(other: MultiSet<T> | MultiSetArray<T>): void {\n const otherArray = other instanceof MultiSet ? other.getInner() : other\n chunkedArrayPush(this.#inner, otherArray)\n }\n\n getInner(): MultiSetArray<T> {\n return this.#inner\n }\n}\n"],"names":["chunkedArrayPush","globalObjectIdGenerator","DefaultMap","hash"],"mappings":";;;;;;;;;;;;;AAaO,MAAM,YAAN,MAAM,UAAY;AAAA,EAGvB,YAAY,OAAyB,IAAI;AAHpC;AACL;AAGE,uBAAK,QAAS;AAAA,EAChB;AAAA,EAEA,SAAS,SAAS,OAAe;AAC/B,WAAO,YAAY,KAAK,UAAU,mBAAK,SAAQ,MAAM,SAAS,IAAI,MAAS,CAAC;AAAA,EAC9E;AAAA,EAEA,SAAiB;AACf,W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AAI,YAAY,GAAI,YAAY,CAAC;AAAA,IACvD;AAAA,EACF;AAEA,SAAO,IAAI,UAAS,MAAM;AAC5B;AAAA;AAAA;AAAA;AAKA,wBAAA,WAAmC;AACjC,QAAM,eAAe,IAAIC,iBAAoC,MAAM,CAAC;AACpE,QAAM,6BAAa,IAAA;AAEnB,MAAI,YAAY;AAChB,MAAI,YAAY;AAChB,MAAI,WAAW;AACf,aAAW,CAAC,MAAM,CAAC,KAAK,mBAAK,SAAQ;AACnC,QAAI,OAAO,SAAS,UAAU;AAC5B,kBAAY;AAAA,IACd,WAAW,OAAO,SAAS,UAAU;AACnC,kBAAY;AAAA,IACd,OAAO;AACL,iBAAW;AACX;AAAA,IACF;AAAA,EACF;AAEA,QAAM,cAAc,YAAa,aAAa;AAE9C,aAAW,CAAC,MAAM,YAAY,KAAK,mBAAK,SAAQ;AAC9C,UAAM,MAAM,cAAcC,UAAK,IAAI,IAAK;AACxC,QAAI,eAAe,CAAC,OAAO,IAAI,GAAa,GAAG;AAC7C,aAAO,IAAI,KAAe,IAAI;AAAA,IAChC;AACA,iBAAa,OAAO,KAAK,CAAC,UAAU,QAAQ,YAAY;AAAA,EAC1D;AAEA,QAAM,SAA2B,CAAA;AACjC,aAAW,CAAC,KAAK,YAAY,KAAK,aAAa,WAAW;AACxD,QAAI,iBAAiB,GAAG;AACtB,YAAM,YAAY,cAAc,OAAO,IAAI,GAAa,IAAI;AAC5D,aAAO,KAAK,CAAC,WAAgB,YAAY,CAAC;AAAA,IAC5C;AAAA,EACF;AAEA,SAAO,IAAI,UAAS,MAAM;AAC5B;AA/LK,IAAM,WAAN;;"}
|
|
1
|
+
{"version":3,"file":"multiset.cjs","sources":["../../src/multiset.ts"],"sourcesContent":["import {\n DefaultMap,\n chunkedArrayPush,\n globalObjectIdGenerator,\n} from \"./utils.js\"\nimport { hash } from \"./hashing/index.js\"\n\nexport type MultiSetArray<T> = Array<[T, number]>\nexport type KeyedData<T> = [key: string, value: T]\n\n/**\n * A multiset of data.\n */\nexport class MultiSet<T> {\n #inner: MultiSetArray<T>\n\n constructor(data: MultiSetArray<T> = []) {\n this.#inner = data\n }\n\n toString(indent = false): string {\n return `MultiSet(${JSON.stringify(this.#inner, null, indent ? 2 : undefined)})`\n }\n\n toJSON(): string {\n return JSON.stringify(Array.from(this.getInner()))\n }\n\n static fromJSON<U>(json: string): MultiSet<U> {\n return new MultiSet(JSON.parse(json))\n }\n\n /**\n * Apply a function to all records in the collection.\n */\n map<U>(f: (data: T) => U): MultiSet<U> {\n return new MultiSet(\n this.#inner.map(([data, multiplicity]) => [f(data), multiplicity])\n )\n }\n\n /**\n * Filter out records for which a function f(record) evaluates to False.\n */\n filter(f: (data: T) => boolean): MultiSet<T> {\n return new MultiSet(this.#inner.filter(([data, _]) => f(data)))\n }\n\n /**\n * Negate all multiplicities in the collection.\n */\n negate(): MultiSet<T> {\n return new MultiSet(\n this.#inner.map(([data, multiplicity]) => [data, -multiplicity])\n )\n }\n\n /**\n * Concatenate two collections together.\n */\n concat(other: MultiSet<T>): MultiSet<T> {\n const out: MultiSetArray<T> = []\n chunkedArrayPush(out, this.#inner)\n chunkedArrayPush(out, other.getInner())\n return new MultiSet(out)\n }\n\n /**\n * Produce as output a collection that is logically equivalent to the input\n * but which combines identical instances of the same record into one\n * (record, multiplicity) pair.\n */\n consolidate(): MultiSet<T> {\n // Check if this looks like a keyed multiset (first item is a tuple of length 2)\n if (this.#inner.length > 0) {\n const firstItem = this.#inner[0]?.[0]\n if (Array.isArray(firstItem) && firstItem.length === 2) {\n return this.#consolidateKeyed()\n }\n }\n\n // Fall back to original method for unkeyed data\n return this.#consolidateUnkeyed()\n }\n\n /**\n * Private method for consolidating keyed multisets where keys are strings/numbers\n * and values are compared by reference equality.\n *\n * This method provides significant performance improvements over the hash-based approach\n * by using WeakMap for object reference tracking and avoiding expensive serialization.\n *\n * Special handling for join operations: When values are tuples of length 2 (common in joins),\n * we unpack them and compare each element individually to maintain proper equality semantics.\n */\n #consolidateKeyed(): MultiSet<T> {\n const consolidated = new Map<string, number>()\n const values = new Map<string, T>()\n\n // Use global object ID generator for consistent reference equality\n\n /**\n * Special handler for tuples (arrays of length 2) commonly produced by join operations.\n * Unpacks the tuple and generates an ID based on both elements to ensure proper\n * consolidation of join results like ['A', null] and [null, 'X'].\n */\n const getTupleId = (tuple: Array<any>): string => {\n if (tuple.length !== 2) {\n throw new Error(`Expected tuple of length 2`)\n }\n const [first, second] = tuple\n return `${globalObjectIdGenerator.getStringId(first)}|${globalObjectIdGenerator.getStringId(second)}`\n }\n\n // Process each item in the multiset\n for (const [data, multiplicity] of this.#inner) {\n // Verify this is still a keyed item (should be [key, value] pair)\n if (!Array.isArray(data) || data.length !== 2) {\n // Found non-keyed item, fall back to unkeyed consolidation\n return this.#consolidateUnkeyed()\n }\n\n const [key, value] = data\n\n // Verify key is string or number as expected for keyed multisets\n if (typeof key !== `string` && typeof key !== `number`) {\n // Found non-string/number key, fall back to unkeyed consolidation\n return this.#consolidateUnkeyed()\n }\n\n // Generate value ID with special handling for join tuples\n let valueId: string\n if (Array.isArray(value) && value.length === 2) {\n // Special case: value is a tuple from join operations\n valueId = getTupleId(value)\n } else {\n // Regular case: use reference/value equality\n valueId = globalObjectIdGenerator.getStringId(value)\n }\n\n // Create composite key and consolidate\n const compositeKey = key + `|` + valueId\n consolidated.set(\n compositeKey,\n (consolidated.get(compositeKey) || 0) + multiplicity\n )\n\n // Store the original data for the first occurrence\n if (!values.has(compositeKey)) {\n values.set(compositeKey, data as T)\n }\n }\n\n // Build result array, filtering out zero multiplicities\n const result: MultiSetArray<T> = []\n for (const [compositeKey, multiplicity] of consolidated) {\n if (multiplicity !== 0) {\n result.push([values.get(compositeKey)!, multiplicity])\n }\n }\n\n return new MultiSet(result)\n }\n\n /**\n * Private method for consolidating unkeyed multisets using the original approach.\n */\n #consolidateUnkeyed(): MultiSet<T> {\n const consolidated = new DefaultMap<string | number, number>(() => 0)\n const values = new Map<string, any>()\n\n let hasString = false\n let hasNumber = false\n let hasOther = false\n for (const [data, _] of this.#inner) {\n if (typeof data === `string`) {\n hasString = true\n } else if (typeof data === `number`) {\n hasNumber = true\n } else {\n hasOther = true\n break\n }\n }\n\n const requireJson = hasOther || (hasString && hasNumber)\n\n for (const [data, multiplicity] of this.#inner) {\n const key = requireJson ? hash(data) : (data as string | number)\n if (requireJson && !values.has(key as string)) {\n values.set(key as string, data)\n }\n consolidated.update(key, (count) => count + multiplicity)\n }\n\n const result: MultiSetArray<T> = []\n for (const [key, multiplicity] of consolidated.entries()) {\n if (multiplicity !== 0) {\n const parsedKey = requireJson ? values.get(key as string) : key\n result.push([parsedKey as T, multiplicity])\n }\n }\n\n return new MultiSet(result)\n }\n\n extend(other: MultiSet<T> | MultiSetArray<T>): void {\n const otherArray = other instanceof MultiSet ? other.getInner() : other\n chunkedArrayPush(this.#inner, otherArray)\n }\n\n add(item: T, multiplicity: number): void {\n if (multiplicity !== 0) {\n this.#inner.push([item, multiplicity])\n }\n }\n\n getInner(): MultiSetArray<T> {\n return this.#inner\n }\n}\n"],"names":["chunkedArrayPush","globalObjectIdGenerator","DefaultMap","hash"],"mappings":";;;;AAaO,MAAM,SAAY;AAAA,EACvB;AAAA,EAEA,YAAY,OAAyB,IAAI;AACvC,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,SAAS,SAAS,OAAe;AAC/B,WAAO,YAAY,KAAK,UAAU,KAAK,QAAQ,MAAM,SAAS,IAAI,MAAS,CAAC;AAAA,EAC9E;AAAA,EAEA,SAAiB;AACf,WAAO,KAAK,UAAU,MAAM,KAAK,KAAK,SAAA,CAAU,CAAC;AAAA,EACnD;AAAA,EAEA,OAAO,SAAY,MAA2B;AAC5C,WAAO,IAAI,SAAS,KAAK,MAAM,IAAI,CAAC;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA,EAKA,IAAO,GAAgC;AACrC,WAAO,IAAI;AAAA,MACT,KAAK,OAAO,IAAI,CAAC,CAAC,MAAM,YAAY,MAAM,CAAC,EAAE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eAAW,CAAC,MAAM,YAAY,KAAK,KAAK,QAAQ;AAC9C,YAAM,MAAM,cAAcC,UAAK,IAAI,IAAK;AACxC,UAAI,eAAe,CAAC,OAAO,IAAI,GAAa,GAAG;AAC7C,eAAO,IAAI,KAAe,IAAI;AAAA,MAChC;AACA,mBAAa,OAAO,KAAK,CAAC,UAAU,QAAQ,YAAY;AAAA,IAC1D;AAEA,UAAM,SAA2B,CAAA;AACjC,eAAW,CAAC,KAAK,YAAY,KAAK,aAAa,WAAW;AACxD,UAAI,iBAAiB,GAAG;AACtB,cAAM,YAAY,cAAc,OAAO,IAAI,GAAa,IAAI;AAC5D,eAAO,KAAK,CAAC,WAAgB,YAAY,CAAC;AAAA,MAC5C;AAAA,IACF;AAEA,WAAO,IAAI,SAAS,MAAM;AAAA,EAC5B;AAAA,EAEA,OAAO,OAA6C;AAClD,UAAM,aAAa,iBAAiB,WAAW,MAAM,aAAa;AAClEH,2BAAiB,KAAK,QAAQ,UAAU;AAAA,EAC1C;AAAA,EAEA,IAAI,MAAS,cAA4B;AACvC,QAAI,iBAAiB,GAAG;AACtB,WAAK,OAAO,KAAK,CAAC,MAAM,YAAY,CAAC;AAAA,IACvC;AAAA,EACF;AAAA,EAEA,WAA6B;AAC3B,WAAO,KAAK;AAAA,EACd;AACF;;"}
|
package/dist/cjs/multiset.d.cts
CHANGED
|
@@ -1,32 +1,22 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __typeError = (msg) => {
|
|
3
|
-
throw TypeError(msg);
|
|
4
|
-
};
|
|
5
|
-
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
6
|
-
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
7
|
-
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
8
|
-
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
9
|
-
var _name, _indent;
|
|
10
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
11
3
|
const graph = require("../graph.cjs");
|
|
12
4
|
const d2 = require("../d2.cjs");
|
|
13
5
|
class DebugOperator extends graph.UnaryOperator {
|
|
6
|
+
#name;
|
|
7
|
+
#indent;
|
|
14
8
|
constructor(id, inputA, output, name, indent = false) {
|
|
15
9
|
super(id, inputA, output);
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
__privateSet(this, _name, name);
|
|
19
|
-
__privateSet(this, _indent, indent);
|
|
10
|
+
this.#name = name;
|
|
11
|
+
this.#indent = indent;
|
|
20
12
|
}
|
|
21
13
|
run() {
|
|
22
14
|
for (const message of this.inputMessages()) {
|
|
23
|
-
console.log(`debug ${
|
|
15
|
+
console.log(`debug ${this.#name} data: ${message.toString(this.#indent)}`);
|
|
24
16
|
this.output.sendData(message);
|
|
25
17
|
}
|
|
26
18
|
}
|
|
27
19
|
}
|
|
28
|
-
_name = new WeakMap();
|
|
29
|
-
_indent = new WeakMap();
|
|
30
20
|
function debug(name, indent = false) {
|
|
31
21
|
return (stream) => {
|
|
32
22
|
const output = new d2.StreamBuilder(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debug.cjs","sources":["../../../src/operators/debug.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from \"../graph.js\"\nimport { StreamBuilder } from \"../d2.js\"\nimport type { IStreamBuilder, PipedOperator } from \"../types.js\"\nimport type { DifferenceStreamReader } from \"../graph.js\"\n\n/**\n * Operator that logs debug information about the stream\n */\nexport class DebugOperator<T> extends UnaryOperator<T> {\n #name: string\n #indent: boolean\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<T>,\n output: DifferenceStreamWriter<T>,\n name: string,\n indent: boolean = false\n ) {\n super(id, inputA, output)\n this.#name = name\n this.#indent = indent\n }\n\n run(): void {\n for (const message of this.inputMessages()) {\n console.log(`debug ${this.#name} data: ${message.toString(this.#indent)}`)\n this.output.sendData(message)\n }\n }\n}\n\n/**\n * Logs debug information about the stream using console.log\n * @param name - The name to prefix debug messages with\n * @param indent - Whether to indent the debug output\n */\nexport function debug<T>(\n name: string,\n indent: boolean = false\n): PipedOperator<T, T> {\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n const output = new StreamBuilder<T>(\n stream.graph,\n new DifferenceStreamWriter<T>()\n )\n const operator = new DebugOperator<T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n name,\n indent\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":["UnaryOperator","StreamBuilder","DifferenceStreamWriter"],"mappings":"
|
|
1
|
+
{"version":3,"file":"debug.cjs","sources":["../../../src/operators/debug.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from \"../graph.js\"\nimport { StreamBuilder } from \"../d2.js\"\nimport type { IStreamBuilder, PipedOperator } from \"../types.js\"\nimport type { DifferenceStreamReader } from \"../graph.js\"\n\n/**\n * Operator that logs debug information about the stream\n */\nexport class DebugOperator<T> extends UnaryOperator<T> {\n #name: string\n #indent: boolean\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<T>,\n output: DifferenceStreamWriter<T>,\n name: string,\n indent: boolean = false\n ) {\n super(id, inputA, output)\n this.#name = name\n this.#indent = indent\n }\n\n run(): void {\n for (const message of this.inputMessages()) {\n console.log(`debug ${this.#name} data: ${message.toString(this.#indent)}`)\n this.output.sendData(message)\n }\n }\n}\n\n/**\n * Logs debug information about the stream using console.log\n * @param name - The name to prefix debug messages with\n * @param indent - Whether to indent the debug output\n */\nexport function debug<T>(\n name: string,\n indent: boolean = false\n): PipedOperator<T, T> {\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n const output = new StreamBuilder<T>(\n stream.graph,\n new DifferenceStreamWriter<T>()\n )\n const operator = new DebugOperator<T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n name,\n indent\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":["UnaryOperator","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;AAQO,MAAM,sBAAyBA,MAAAA,cAAiB;AAAA,EACrD;AAAA,EACA;AAAA,EAEA,YACE,IACA,QACA,QACA,MACA,SAAkB,OAClB;AACA,UAAM,IAAI,QAAQ,MAAM;AACxB,SAAK,QAAQ;AACb,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAY;AACV,eAAW,WAAW,KAAK,iBAAiB;AAC1C,cAAQ,IAAI,SAAS,KAAK,KAAK,UAAU,QAAQ,SAAS,KAAK,OAAO,CAAC,EAAE;AACzE,WAAK,OAAO,SAAS,OAAO;AAAA,IAC9B;AAAA,EACF;AACF;AAOO,SAAS,MACd,MACA,SAAkB,OACG;AACrB,SAAO,CAAC,WAAiD;AACvD,UAAM,SAAS,IAAIC,GAAAA;AAAAA,MACjB,OAAO;AAAA,MACP,IAAIC,MAAAA,uBAAA;AAAA,IAA0B;AAEhC,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,MACA;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;;;"}
|
|
@@ -1,33 +1,24 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __typeError = (msg) => {
|
|
3
|
-
throw TypeError(msg);
|
|
4
|
-
};
|
|
5
|
-
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
6
|
-
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
7
|
-
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
8
|
-
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
9
|
-
var _by, _values;
|
|
10
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
11
3
|
const graph = require("../graph.cjs");
|
|
12
4
|
const d2 = require("../d2.cjs");
|
|
13
5
|
const multiset = require("../multiset.cjs");
|
|
14
6
|
const hash = require("../hashing/hash.cjs");
|
|
15
7
|
class DistinctOperator extends graph.UnaryOperator {
|
|
8
|
+
#by;
|
|
9
|
+
#values;
|
|
16
10
|
// keeps track of the number of times each value has been seen
|
|
17
11
|
constructor(id, input, output, by = (value) => value) {
|
|
18
12
|
super(id, input, output);
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
__privateSet(this, _by, by);
|
|
22
|
-
__privateSet(this, _values, /* @__PURE__ */ new Map());
|
|
13
|
+
this.#by = by;
|
|
14
|
+
this.#values = /* @__PURE__ */ new Map();
|
|
23
15
|
}
|
|
24
16
|
run() {
|
|
25
|
-
var _a;
|
|
26
17
|
const updatedValues = /* @__PURE__ */ new Map();
|
|
27
18
|
for (const message of this.inputMessages()) {
|
|
28
19
|
for (const [value, diff] of message.getInner()) {
|
|
29
|
-
const hashedValue = hash.hash(
|
|
30
|
-
const oldMultiplicity =
|
|
20
|
+
const hashedValue = hash.hash(this.#by(value));
|
|
21
|
+
const oldMultiplicity = updatedValues.get(hashedValue)?.[0] ?? this.#values.get(hashedValue) ?? 0;
|
|
31
22
|
const newMultiplicity = oldMultiplicity + diff;
|
|
32
23
|
updatedValues.set(hashedValue, [newMultiplicity, value]);
|
|
33
24
|
}
|
|
@@ -37,16 +28,16 @@ class DistinctOperator extends graph.UnaryOperator {
|
|
|
37
28
|
hashedValue,
|
|
38
29
|
[newMultiplicity, value]
|
|
39
30
|
] of updatedValues.entries()) {
|
|
40
|
-
const oldMultiplicity =
|
|
31
|
+
const oldMultiplicity = this.#values.get(hashedValue) ?? 0;
|
|
41
32
|
if (newMultiplicity === 0) {
|
|
42
|
-
|
|
33
|
+
this.#values.delete(hashedValue);
|
|
43
34
|
} else {
|
|
44
|
-
|
|
35
|
+
this.#values.set(hashedValue, newMultiplicity);
|
|
45
36
|
}
|
|
46
37
|
if (oldMultiplicity <= 0 && newMultiplicity > 0) {
|
|
47
|
-
result.push([[hash.hash(
|
|
38
|
+
result.push([[hash.hash(this.#by(value)), value[1]], 1]);
|
|
48
39
|
} else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
|
|
49
|
-
result.push([[hash.hash(
|
|
40
|
+
result.push([[hash.hash(this.#by(value)), value[1]], -1]);
|
|
50
41
|
}
|
|
51
42
|
}
|
|
52
43
|
if (result.length > 0) {
|
|
@@ -54,8 +45,6 @@ class DistinctOperator extends graph.UnaryOperator {
|
|
|
54
45
|
}
|
|
55
46
|
}
|
|
56
47
|
}
|
|
57
|
-
_by = new WeakMap();
|
|
58
|
-
_values = new WeakMap();
|
|
59
48
|
function distinct(by = (value) => value) {
|
|
60
49
|
return (stream) => {
|
|
61
50
|
const output = new d2.StreamBuilder(
|