@tanstack/db-ivm 0.1.2 → 0.1.3
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/hashIndex.cjs +83 -0
- package/dist/cjs/hashIndex.cjs.map +1 -0
- package/dist/cjs/hashIndex.d.cts +25 -0
- package/dist/cjs/hashing/hash.cjs +122 -0
- package/dist/cjs/hashing/hash.cjs.map +1 -0
- package/dist/cjs/hashing/hash.d.cts +1 -0
- package/dist/cjs/hashing/index.d.cts +2 -0
- package/dist/cjs/hashing/murmur.cjs +103 -0
- package/dist/cjs/hashing/murmur.cjs.map +1 -0
- package/dist/cjs/hashing/murmur.d.cts +26 -0
- package/dist/cjs/indexes.cjs +97 -45
- package/dist/cjs/indexes.cjs.map +1 -1
- package/dist/cjs/indexes.d.cts +0 -2
- package/dist/cjs/multiset.cjs +2 -1
- package/dist/cjs/multiset.cjs.map +1 -1
- package/dist/cjs/operators/distinct.cjs +2 -2
- package/dist/cjs/operators/distinct.cjs.map +1 -1
- package/dist/cjs/operators/groupBy.cjs +5 -4
- package/dist/cjs/operators/groupBy.cjs.map +1 -1
- package/dist/cjs/operators/groupBy.d.cts +1 -1
- package/dist/cjs/utils.cjs +13 -33
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +7 -4
- package/dist/cjs/valueIndex.cjs +74 -0
- package/dist/cjs/valueIndex.cjs.map +1 -0
- package/dist/cjs/valueIndex.d.cts +17 -0
- package/dist/esm/hashIndex.d.ts +25 -0
- package/dist/esm/hashIndex.js +83 -0
- package/dist/esm/hashIndex.js.map +1 -0
- package/dist/esm/hashing/hash.d.ts +1 -0
- package/dist/esm/hashing/hash.js +122 -0
- package/dist/esm/hashing/hash.js.map +1 -0
- package/dist/esm/hashing/index.d.ts +2 -0
- package/dist/esm/hashing/murmur.d.ts +26 -0
- package/dist/esm/hashing/murmur.js +103 -0
- package/dist/esm/hashing/murmur.js.map +1 -0
- package/dist/esm/indexes.d.ts +0 -2
- package/dist/esm/indexes.js +98 -46
- package/dist/esm/indexes.js.map +1 -1
- package/dist/esm/multiset.js +2 -1
- package/dist/esm/multiset.js.map +1 -1
- package/dist/esm/operators/distinct.js +1 -1
- package/dist/esm/operators/distinct.js.map +1 -1
- package/dist/esm/operators/groupBy.d.ts +1 -1
- package/dist/esm/operators/groupBy.js +5 -4
- package/dist/esm/operators/groupBy.js.map +1 -1
- package/dist/esm/utils.d.ts +7 -4
- package/dist/esm/utils.js +13 -33
- package/dist/esm/utils.js.map +1 -1
- package/dist/esm/valueIndex.d.ts +17 -0
- package/dist/esm/valueIndex.js +74 -0
- package/dist/esm/valueIndex.js.map +1 -0
- package/package.json +1 -3
- package/src/hashIndex.ts +94 -0
- package/src/hashing/hash.ts +157 -0
- package/src/hashing/index.ts +2 -0
- package/src/hashing/murmur.ts +128 -0
- package/src/indexes.ts +106 -47
- package/src/multiset.ts +1 -1
- package/src/operators/distinct.ts +4 -4
- package/src/operators/groupBy.ts +7 -4
- package/src/utils.ts +31 -48
- package/src/valueIndex.ts +78 -0
|
@@ -26,7 +26,7 @@ export declare function sum<T>(valueExtractor?: (value: T) => number): Aggregate
|
|
|
26
26
|
/**
|
|
27
27
|
* Creates a count aggregate function
|
|
28
28
|
*/
|
|
29
|
-
export declare function count<T>(): AggregateFunction<T, number, number>;
|
|
29
|
+
export declare function count<T>(valueExtractor?: (value: T) => any): AggregateFunction<T, number, number>;
|
|
30
30
|
/**
|
|
31
31
|
* Creates an average aggregate function
|
|
32
32
|
*/
|
|
@@ -79,13 +79,14 @@ function sum(valueExtractor = (v) => v) {
|
|
|
79
79
|
}
|
|
80
80
|
};
|
|
81
81
|
}
|
|
82
|
-
function count() {
|
|
82
|
+
function count(valueExtractor = (v) => v) {
|
|
83
83
|
return {
|
|
84
|
-
|
|
84
|
+
// Count only not-null values (the `== null` comparison gives true for both null and undefined)
|
|
85
|
+
preMap: (data) => valueExtractor(data) == null ? 0 : 1,
|
|
85
86
|
reduce: (values) => {
|
|
86
87
|
let totalCount = 0;
|
|
87
|
-
for (const [
|
|
88
|
-
totalCount += multiplicity;
|
|
88
|
+
for (const [nullMultiplier, multiplicity] of values) {
|
|
89
|
+
totalCount += nullMultiplier * multiplicity;
|
|
89
90
|
}
|
|
90
91
|
return totalCount;
|
|
91
92
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupBy.js","sources":["../../../src/operators/groupBy.ts"],"sourcesContent":["import { map } from \"./map.js\"\nimport { reduce } from \"./reduce.js\"\nimport type { IStreamBuilder, KeyValue } from \"../types.js\"\n\ntype GroupKey = Record<string, unknown>\n\ntype BasicAggregateFunction<T, R, V = unknown> = {\n preMap: (data: T) => V\n reduce: (values: Array<[V, number]>) => V\n postMap?: (result: V) => R\n}\n\ntype PipedAggregateFunction<T, R> = {\n pipe: (stream: IStreamBuilder<T>) => IStreamBuilder<KeyValue<string, R>>\n}\n\ntype AggregateFunction<T, R, V = unknown> =\n | BasicAggregateFunction<T, R, V>\n | PipedAggregateFunction<T, R>\n\ntype ExtractAggregateReturnType<T, A> =\n A extends AggregateFunction<T, infer R, any> ? R : never\n\ntype AggregatesReturnType<T, A> = {\n [K in keyof A]: ExtractAggregateReturnType<T, A[K]>\n}\n\nfunction isPipedAggregateFunction<T, R>(\n aggregate: AggregateFunction<T, R>\n): aggregate is PipedAggregateFunction<T, R> {\n return `pipe` in aggregate\n}\n\n/**\n * Groups data by key and applies multiple aggregate operations\n * @param keyExtractor Function to extract grouping key from data\n * @param aggregates Object mapping aggregate names to aggregate functions\n */\nexport function groupBy<\n T,\n K extends GroupKey,\n A extends Record<string, AggregateFunction<T, any, any>>,\n>(keyExtractor: (data: T) => K, aggregates: A = {} as A) {\n type ResultType = K & AggregatesReturnType<T, A>\n\n const basicAggregates = Object.fromEntries(\n Object.entries(aggregates).filter(\n ([_, aggregate]) => !isPipedAggregateFunction(aggregate)\n )\n ) as Record<string, BasicAggregateFunction<T, any, any>>\n\n // @ts-expect-error - TODO: we don't use this yet, but we will\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const pipedAggregates = Object.fromEntries(\n Object.entries(aggregates).filter(([_, aggregate]) =>\n isPipedAggregateFunction(aggregate)\n )\n ) as Record<string, PipedAggregateFunction<T, any>>\n\n return (\n stream: IStreamBuilder<T>\n ): IStreamBuilder<KeyValue<string, ResultType>> => {\n // Special key to store the original key object\n const KEY_SENTINEL = `__original_key__`\n\n // First map to extract keys and pre-aggregate values\n const withKeysAndValues = stream.pipe(\n map((data) => {\n const key = keyExtractor(data)\n const keyString = JSON.stringify(key)\n\n // Create values object with pre-aggregated values\n const values: Record<string, unknown> = {}\n\n // Store the original key object\n values[KEY_SENTINEL] = key\n\n // Add pre-aggregated values\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n values[name] = aggregate.preMap(data)\n }\n\n return [keyString, values] as KeyValue<string, Record<string, unknown>>\n })\n )\n\n // Then reduce to compute aggregates\n const reduced = withKeysAndValues.pipe(\n reduce((values) => {\n // Calculate total multiplicity to check if the group should exist\n let totalMultiplicity = 0\n for (const [_, multiplicity] of values) {\n totalMultiplicity += multiplicity\n }\n\n // If total multiplicity is 0 or negative, the group should be removed completely\n if (totalMultiplicity <= 0) {\n return []\n }\n\n const result: Record<string, unknown> = {}\n\n // Get the original key from first value in group\n const originalKey = values[0]?.[0]?.[KEY_SENTINEL]\n result[KEY_SENTINEL] = originalKey\n\n // Apply each aggregate function\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n const preValues = values.map(\n ([v, m]) => [v[name], m] as [any, number]\n )\n result[name] = aggregate.reduce(preValues)\n }\n\n return [[result, 1]]\n })\n )\n\n // Finally map to extract the key and include all values\n return reduced.pipe(\n map(([keyString, values]) => {\n // Extract the original key\n const key = values[KEY_SENTINEL] as K\n\n // Create intermediate result with key values and aggregate results\n const result: Record<string, unknown> = {}\n\n // Add key properties to result\n Object.assign(result, key)\n\n // Apply postMap if provided\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n if (aggregate.postMap) {\n result[name] = aggregate.postMap(values[name])\n } else {\n result[name] = values[name]\n }\n }\n\n // Return with the string key instead of the object\n return [keyString, result] as KeyValue<string, ResultType>\n })\n )\n }\n}\n\n/**\n * Creates a sum aggregate function\n */\nexport function sum<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, number> {\n return {\n preMap: (data: T) => valueExtractor(data),\n reduce: (values: Array<[number, number]>) => {\n let total = 0\n for (const [value, multiplicity] of values) {\n total += value * multiplicity\n }\n return total\n },\n }\n}\n\n/**\n * Creates a count aggregate function\n */\nexport function count<T>(): AggregateFunction<T, number, number> {\n return {\n preMap: () => 1,\n reduce: (values: Array<[number, number]>) => {\n let totalCount = 0\n for (const [_, multiplicity] of values) {\n totalCount += multiplicity\n }\n return totalCount\n },\n }\n}\n\n/**\n * Creates an average aggregate function\n */\nexport function avg<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, { sum: number; count: number }> {\n return {\n preMap: (data: T) => ({\n sum: valueExtractor(data),\n count: 0,\n }),\n reduce: (values: Array<[{ sum: number; count: number }, number]>) => {\n let totalSum = 0\n let totalCount = 0\n for (const [value, multiplicity] of values) {\n totalSum += value.sum * multiplicity\n totalCount += multiplicity\n }\n return {\n sum: totalSum,\n count: totalCount,\n }\n },\n postMap: (result: { sum: number; count: number }) => {\n return result.sum / result.count\n },\n }\n}\n\n/**\n * Creates a min aggregate function that computes the minimum value in a group\n * @param valueExtractor Function to extract a numeric value from each data entry\n */\nexport function min<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, number> {\n return {\n preMap: (data: T) => valueExtractor(data),\n reduce: (values: Array<[number, number]>) => {\n let minValue = Number.POSITIVE_INFINITY\n for (const [value, _multiplicity] of values) {\n if (value < minValue) {\n minValue = value\n }\n }\n return minValue === Number.POSITIVE_INFINITY ? 0 : minValue\n },\n }\n}\n\n/**\n * Creates a max aggregate function that computes the maximum value in a group\n * @param valueExtractor Function to extract a numeric value from each data entry\n */\nexport function max<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, number> {\n return {\n preMap: (data: T) => valueExtractor(data),\n reduce: (values: Array<[number, number]>) => {\n let maxValue = Number.NEGATIVE_INFINITY\n for (const [value, _multiplicity] of values) {\n if (value > maxValue) {\n maxValue = value\n }\n }\n return maxValue === Number.NEGATIVE_INFINITY ? 0 : maxValue\n },\n }\n}\n\n/**\n * Creates a median aggregate function that computes the middle value in a sorted group\n * If there's an even number of values, returns the average of the two middle values\n * @param valueExtractor Function to extract a numeric value from each data entry\n */\nexport function median<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, Array<number>> {\n return {\n preMap: (data: T) => [valueExtractor(data)],\n reduce: (values: Array<[Array<number>, number]>) => {\n // Flatten all values, taking multiplicity into account\n const allValues: Array<number> = []\n for (const [valueArray, multiplicity] of values) {\n for (const value of valueArray) {\n // Add each value multiple times based on multiplicity\n for (let i = 0; i < multiplicity; i++) {\n allValues.push(value)\n }\n }\n }\n\n // Return empty array if no values\n if (allValues.length === 0) {\n return []\n }\n\n // Sort values\n allValues.sort((a, b) => a - b)\n\n return allValues\n },\n postMap: (result: Array<number>) => {\n if (result.length === 0) return 0\n\n const mid = Math.floor(result.length / 2)\n\n // If even number of values, average the two middle values\n if (result.length % 2 === 0) {\n return (result[mid - 1]! + result[mid]!) / 2\n }\n\n // If odd number of values, return the middle value\n return result[mid]!\n },\n }\n}\n\n/**\n * Creates a mode aggregate function that computes the most frequent value in a group\n * If multiple values have the same highest frequency, returns the first one encountered\n * @param valueExtractor Function to extract a value from each data entry\n */\nexport function mode<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, Map<number, number>> {\n return {\n preMap: (data: T) => {\n const value = valueExtractor(data)\n const frequencyMap = new Map<number, number>()\n frequencyMap.set(value, 1)\n return frequencyMap\n },\n reduce: (values: Array<[Map<number, number>, number]>) => {\n // Combine all frequency maps\n const combinedMap = new Map<number, number>()\n\n for (const [frequencyMap, multiplicity] of values) {\n for (const [value, frequencyCount] of frequencyMap.entries()) {\n const currentCount = combinedMap.get(value) || 0\n combinedMap.set(value, currentCount + frequencyCount * multiplicity)\n }\n }\n\n return combinedMap\n },\n postMap: (result: Map<number, number>) => {\n if (result.size === 0) return 0\n\n let modeValue = 0\n let maxFrequency = 0\n\n for (const [value, frequency] of result.entries()) {\n if (frequency > maxFrequency) {\n maxFrequency = frequency\n modeValue = value\n }\n }\n\n return modeValue\n },\n }\n}\n\nexport const groupByOperators = {\n sum,\n count,\n avg,\n min,\n max,\n median,\n mode,\n}\n"],"names":[],"mappings":";;AA2BA,SAAS,yBACP,WAC2C;AAC3C,SAAO,UAAU;AACnB;AAOO,SAAS,QAId,cAA8B,aAAgB,IAAS;AAGvD,QAAM,kBAAkB,OAAO;AAAA,IAC7B,OAAO,QAAQ,UAAU,EAAE;AAAA,MACzB,CAAC,CAAC,GAAG,SAAS,MAAM,CAAC,yBAAyB,SAAS;AAAA,IAAA;AAAA,EACzD;AAKsB,SAAO;AAAA,IAC7B,OAAO,QAAQ,UAAU,EAAE;AAAA,MAAO,CAAC,CAAC,GAAG,SAAS,MAC9C,yBAAyB,SAAS;AAAA,IAAA;AAAA,EACpC;AAGF,SAAO,CACL,WACiD;AAEjD,UAAM,eAAe;AAGrB,UAAM,oBAAoB,OAAO;AAAA,MAC/B,IAAI,CAAC,SAAS;AACZ,cAAM,MAAM,aAAa,IAAI;AAC7B,cAAM,YAAY,KAAK,UAAU,GAAG;AAGpC,cAAM,SAAkC,CAAA;AAGxC,eAAO,YAAY,IAAI;AAGvB,mBAAW,CAAC,MAAM,SAAS,KAAK,OAAO,QAAQ,eAAe,GAAG;AAC/D,iBAAO,IAAI,IAAI,UAAU,OAAO,IAAI;AAAA,QACtC;AAEA,eAAO,CAAC,WAAW,MAAM;AAAA,MAC3B,CAAC;AAAA,IAAA;AAI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,IAAA;AAExB,iBAAW,CAAC,cAAc,YAAY,KAAK,QAAQ;AACjD,mBAAW,CAAC,OAAO,cAAc,KAAK,aAAa,WAAW;AAC5D,gBAAM,eAAe,YAAY,IAAI,KAAK,KAAK;AAC/C,sBAAY,IAAI,OAAO,eAAe,iBAAiB,YAAY;AAAA,QACrE;AAAA,MACF;AAEA,aAAO;AAAA,IACT;AAAA,IACA,SAAS,CAAC,WAAgC;AACxC,UAAI,OAAO,SAAS,EAAG,QAAO;AAE9B,UAAI,YAAY;AAChB,UAAI,eAAe;AAEnB,iBAAW,CAAC,OAAO,SAAS,KAAK,OAAO,WAAW;AACjD,YAAI,YAAY,cAAc;AAC5B,yBAAe;AACf,sBAAY;AAAA,QACd;AAAA,MACF;AAEA,aAAO;AAAA,IACT;AAAA,EAAA;AAEJ;AAEO,MAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;"}
|
|
1
|
+
{"version":3,"file":"groupBy.js","sources":["../../../src/operators/groupBy.ts"],"sourcesContent":["import { map } from \"./map.js\"\nimport { reduce } from \"./reduce.js\"\nimport type { IStreamBuilder, KeyValue } from \"../types.js\"\n\ntype GroupKey = Record<string, unknown>\n\ntype BasicAggregateFunction<T, R, V = unknown> = {\n preMap: (data: T) => V\n reduce: (values: Array<[V, number]>) => V\n postMap?: (result: V) => R\n}\n\ntype PipedAggregateFunction<T, R> = {\n pipe: (stream: IStreamBuilder<T>) => IStreamBuilder<KeyValue<string, R>>\n}\n\ntype AggregateFunction<T, R, V = unknown> =\n | BasicAggregateFunction<T, R, V>\n | PipedAggregateFunction<T, R>\n\ntype ExtractAggregateReturnType<T, A> =\n A extends AggregateFunction<T, infer R, any> ? R : never\n\ntype AggregatesReturnType<T, A> = {\n [K in keyof A]: ExtractAggregateReturnType<T, A[K]>\n}\n\nfunction isPipedAggregateFunction<T, R>(\n aggregate: AggregateFunction<T, R>\n): aggregate is PipedAggregateFunction<T, R> {\n return `pipe` in aggregate\n}\n\n/**\n * Groups data by key and applies multiple aggregate operations\n * @param keyExtractor Function to extract grouping key from data\n * @param aggregates Object mapping aggregate names to aggregate functions\n */\nexport function groupBy<\n T,\n K extends GroupKey,\n A extends Record<string, AggregateFunction<T, any, any>>,\n>(keyExtractor: (data: T) => K, aggregates: A = {} as A) {\n type ResultType = K & AggregatesReturnType<T, A>\n\n const basicAggregates = Object.fromEntries(\n Object.entries(aggregates).filter(\n ([_, aggregate]) => !isPipedAggregateFunction(aggregate)\n )\n ) as Record<string, BasicAggregateFunction<T, any, any>>\n\n // @ts-expect-error - TODO: we don't use this yet, but we will\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const pipedAggregates = Object.fromEntries(\n Object.entries(aggregates).filter(([_, aggregate]) =>\n isPipedAggregateFunction(aggregate)\n )\n ) as Record<string, PipedAggregateFunction<T, any>>\n\n return (\n stream: IStreamBuilder<T>\n ): IStreamBuilder<KeyValue<string, ResultType>> => {\n // Special key to store the original key object\n const KEY_SENTINEL = `__original_key__`\n\n // First map to extract keys and pre-aggregate values\n const withKeysAndValues = stream.pipe(\n map((data) => {\n const key = keyExtractor(data)\n const keyString = JSON.stringify(key)\n\n // Create values object with pre-aggregated values\n const values: Record<string, unknown> = {}\n\n // Store the original key object\n values[KEY_SENTINEL] = key\n\n // Add pre-aggregated values\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n values[name] = aggregate.preMap(data)\n }\n\n return [keyString, values] as KeyValue<string, Record<string, unknown>>\n })\n )\n\n // Then reduce to compute aggregates\n const reduced = withKeysAndValues.pipe(\n reduce((values) => {\n // Calculate total multiplicity to check if the group should exist\n let totalMultiplicity = 0\n for (const [_, multiplicity] of values) {\n totalMultiplicity += multiplicity\n }\n\n // If total multiplicity is 0 or negative, the group should be removed completely\n if (totalMultiplicity <= 0) {\n return []\n }\n\n const result: Record<string, unknown> = {}\n\n // Get the original key from first value in group\n const originalKey = values[0]?.[0]?.[KEY_SENTINEL]\n result[KEY_SENTINEL] = originalKey\n\n // Apply each aggregate function\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n const preValues = values.map(\n ([v, m]) => [v[name], m] as [any, number]\n )\n result[name] = aggregate.reduce(preValues)\n }\n\n return [[result, 1]]\n })\n )\n\n // Finally map to extract the key and include all values\n return reduced.pipe(\n map(([keyString, values]) => {\n // Extract the original key\n const key = values[KEY_SENTINEL] as K\n\n // Create intermediate result with key values and aggregate results\n const result: Record<string, unknown> = {}\n\n // Add key properties to result\n Object.assign(result, key)\n\n // Apply postMap if provided\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n if (aggregate.postMap) {\n result[name] = aggregate.postMap(values[name])\n } else {\n result[name] = values[name]\n }\n }\n\n // Return with the string key instead of the object\n return [keyString, result] as KeyValue<string, ResultType>\n })\n )\n }\n}\n\n/**\n * Creates a sum aggregate function\n */\nexport function sum<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, number> {\n return {\n preMap: (data: T) => valueExtractor(data),\n reduce: (values: Array<[number, number]>) => {\n let total = 0\n for (const [value, multiplicity] of values) {\n total += value * multiplicity\n }\n return total\n },\n }\n}\n\n/**\n * Creates a count aggregate function\n */\nexport function count<T>(\n valueExtractor: (value: T) => any = (v) => v\n): AggregateFunction<T, number, number> {\n return {\n // Count only not-null values (the `== null` comparison gives true for both null and undefined)\n preMap: (data: T) => (valueExtractor(data) == null ? 0 : 1),\n reduce: (values: Array<[number, number]>) => {\n let totalCount = 0\n for (const [nullMultiplier, multiplicity] of values) {\n totalCount += nullMultiplier * multiplicity\n }\n return totalCount\n },\n }\n}\n\n/**\n * Creates an average aggregate function\n */\nexport function avg<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, { sum: number; count: number }> {\n return {\n preMap: (data: T) => ({\n sum: valueExtractor(data),\n count: 0,\n }),\n reduce: (values: Array<[{ sum: number; count: number }, number]>) => {\n let totalSum = 0\n let totalCount = 0\n for (const [value, multiplicity] of values) {\n totalSum += value.sum * multiplicity\n totalCount += multiplicity\n }\n return {\n sum: totalSum,\n count: totalCount,\n }\n },\n postMap: (result: { sum: number; count: number }) => {\n return result.sum / result.count\n },\n }\n}\n\n/**\n * Creates a min aggregate function that computes the minimum value in a group\n * @param valueExtractor Function to extract a numeric value from each data entry\n */\nexport function min<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, number> {\n return {\n preMap: (data: T) => valueExtractor(data),\n reduce: (values: Array<[number, number]>) => {\n let minValue = Number.POSITIVE_INFINITY\n for (const [value, _multiplicity] of values) {\n if (value < minValue) {\n minValue = value\n }\n }\n return minValue === Number.POSITIVE_INFINITY ? 0 : minValue\n },\n }\n}\n\n/**\n * Creates a max aggregate function that computes the maximum value in a group\n * @param valueExtractor Function to extract a numeric value from each data entry\n */\nexport function max<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, number> {\n return {\n preMap: (data: T) => valueExtractor(data),\n reduce: (values: Array<[number, number]>) => {\n let maxValue = Number.NEGATIVE_INFINITY\n for (const [value, _multiplicity] of values) {\n if (value > maxValue) {\n maxValue = value\n }\n }\n return maxValue === Number.NEGATIVE_INFINITY ? 0 : maxValue\n },\n }\n}\n\n/**\n * Creates a median aggregate function that computes the middle value in a sorted group\n * If there's an even number of values, returns the average of the two middle values\n * @param valueExtractor Function to extract a numeric value from each data entry\n */\nexport function median<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, Array<number>> {\n return {\n preMap: (data: T) => [valueExtractor(data)],\n reduce: (values: Array<[Array<number>, number]>) => {\n // Flatten all values, taking multiplicity into account\n const allValues: Array<number> = []\n for (const [valueArray, multiplicity] of values) {\n for (const value of valueArray) {\n // Add each value multiple times based on multiplicity\n for (let i = 0; i < multiplicity; i++) {\n allValues.push(value)\n }\n }\n }\n\n // Return empty array if no values\n if (allValues.length === 0) {\n return []\n }\n\n // Sort values\n allValues.sort((a, b) => a - b)\n\n return allValues\n },\n postMap: (result: Array<number>) => {\n if (result.length === 0) return 0\n\n const mid = Math.floor(result.length / 2)\n\n // If even number of values, average the two middle values\n if (result.length % 2 === 0) {\n return (result[mid - 1]! + result[mid]!) / 2\n }\n\n // If odd number of values, return the middle value\n return result[mid]!\n },\n }\n}\n\n/**\n * Creates a mode aggregate function that computes the most frequent value in a group\n * If multiple values have the same highest frequency, returns the first one encountered\n * @param valueExtractor Function to extract a value from each data entry\n */\nexport function mode<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number\n): AggregateFunction<T, number, Map<number, number>> {\n return {\n preMap: (data: T) => {\n const value = valueExtractor(data)\n const frequencyMap = new Map<number, number>()\n frequencyMap.set(value, 1)\n return frequencyMap\n },\n reduce: (values: Array<[Map<number, number>, number]>) => {\n // Combine all frequency maps\n const combinedMap = new Map<number, number>()\n\n for (const [frequencyMap, multiplicity] of values) {\n for (const [value, frequencyCount] of frequencyMap.entries()) {\n const currentCount = combinedMap.get(value) || 0\n combinedMap.set(value, currentCount + frequencyCount * multiplicity)\n }\n }\n\n return combinedMap\n },\n postMap: (result: Map<number, number>) => {\n if (result.size === 0) return 0\n\n let modeValue = 0\n let maxFrequency = 0\n\n for (const [value, frequency] of result.entries()) {\n if (frequency > maxFrequency) {\n maxFrequency = frequency\n modeValue = value\n }\n }\n\n return modeValue\n },\n }\n}\n\nexport const groupByOperators = {\n sum,\n count,\n avg,\n min,\n max,\n median,\n mode,\n}\n"],"names":[],"mappings":";;AA2BA,SAAS,yBACP,WAC2C;AAC3C,SAAO,UAAU;AACnB;AAOO,SAAS,QAId,cAA8B,aAAgB,IAAS;AAGvD,QAAM,kBAAkB,OAAO;AAAA,IAC7B,OAAO,QAAQ,UAAU,EAAE;AAAA,MACzB,CAAC,CAAC,GAAG,SAAS,MAAM,CAAC,yBAAyB,SAAS;AAAA,IAAA;AAAA,EACzD;AAKsB,SAAO;AAAA,IAC7B,OAAO,QAAQ,UAAU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@@
|
|
|
1
|
+
/**
|
|
2
|
+
* Simple assertion function for runtime checks.
|
|
3
|
+
* Throws an error if the condition is false.
|
|
4
|
+
*/
|
|
5
|
+
export declare function assert(condition: unknown, message?: string): asserts condition;
|
|
1
6
|
/**
|
|
2
7
|
* A map that returns a default value for keys that are not present.
|
|
3
8
|
*/
|
|
@@ -11,10 +16,6 @@ export declare class DefaultMap<K, V> extends Map<K, V> {
|
|
|
11
16
|
update(key: K, updater: (value: V) => V): V;
|
|
12
17
|
}
|
|
13
18
|
export declare function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>): void;
|
|
14
|
-
/**
|
|
15
|
-
* A hash method that caches the hash of a value in a week map
|
|
16
|
-
*/
|
|
17
|
-
export declare function hash(data: any): string;
|
|
18
19
|
export declare function binarySearch<T>(array: Array<T>, value: T, comparator: (a: T, b: T) => number): number;
|
|
19
20
|
/**
|
|
20
21
|
* Utility for generating unique IDs for objects and values.
|
|
@@ -38,3 +39,5 @@ export declare class ObjectIdGenerator {
|
|
|
38
39
|
* Global instance for cases where a shared object ID space is needed.
|
|
39
40
|
*/
|
|
40
41
|
export declare const globalObjectIdGenerator: ObjectIdGenerator;
|
|
42
|
+
export declare function concatIterable<T>(...iterables: Array<Iterable<T>>): Iterable<T>;
|
|
43
|
+
export declare function mapIterable<T, U>(it: Iterable<T>, fn: (t: T) => U): Iterable<U>;
|
package/dist/esm/utils.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import murmurhash from "murmurhash-js";
|
|
2
1
|
class DefaultMap extends Map {
|
|
3
2
|
constructor(defaultValue, entries) {
|
|
4
3
|
super(entries);
|
|
@@ -6,7 +5,7 @@ class DefaultMap extends Map {
|
|
|
6
5
|
}
|
|
7
6
|
get(key) {
|
|
8
7
|
if (!this.has(key)) {
|
|
9
|
-
|
|
8
|
+
return this.defaultValue();
|
|
10
9
|
}
|
|
11
10
|
return super.get(key);
|
|
12
11
|
}
|
|
@@ -31,36 +30,6 @@ function chunkedArrayPush(array, other) {
|
|
|
31
30
|
}
|
|
32
31
|
}
|
|
33
32
|
}
|
|
34
|
-
const hashCache = /* @__PURE__ */ new WeakMap();
|
|
35
|
-
function hashReplacer(_key, value) {
|
|
36
|
-
if (typeof value === `bigint`) {
|
|
37
|
-
return String(value);
|
|
38
|
-
} else if (typeof value === `symbol`) {
|
|
39
|
-
return String(value);
|
|
40
|
-
} else if (typeof value === `function`) {
|
|
41
|
-
return String(value);
|
|
42
|
-
} else if (value === void 0) {
|
|
43
|
-
return `undefined`;
|
|
44
|
-
} else if (value instanceof Map) {
|
|
45
|
-
return `Map(${JSON.stringify(Array.from(value.entries()), hashReplacer)})`;
|
|
46
|
-
} else if (value instanceof Set) {
|
|
47
|
-
return `Set(${JSON.stringify(Array.from(value.values()), hashReplacer)})`;
|
|
48
|
-
}
|
|
49
|
-
return value;
|
|
50
|
-
}
|
|
51
|
-
function hash(data) {
|
|
52
|
-
if (data === null || data === void 0 || typeof data !== `object` && typeof data !== `function`) {
|
|
53
|
-
const serialized2 = JSON.stringify(data, hashReplacer);
|
|
54
|
-
return murmurhash.murmur3(serialized2).toString(16);
|
|
55
|
-
}
|
|
56
|
-
if (hashCache.has(data)) {
|
|
57
|
-
return hashCache.get(data);
|
|
58
|
-
}
|
|
59
|
-
const serialized = JSON.stringify(data, hashReplacer);
|
|
60
|
-
const hashValue = murmurhash.murmur3(serialized).toString(16);
|
|
61
|
-
hashCache.set(data, hashValue);
|
|
62
|
-
return hashValue;
|
|
63
|
-
}
|
|
64
33
|
function binarySearch(array, value, comparator) {
|
|
65
34
|
let low = 0;
|
|
66
35
|
let high = array.length;
|
|
@@ -114,12 +83,23 @@ class ObjectIdGenerator {
|
|
|
114
83
|
}
|
|
115
84
|
}
|
|
116
85
|
const globalObjectIdGenerator = new ObjectIdGenerator();
|
|
86
|
+
function* concatIterable(...iterables) {
|
|
87
|
+
for (const iterable of iterables) {
|
|
88
|
+
yield* iterable;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function* mapIterable(it, fn) {
|
|
92
|
+
for (const t of it) {
|
|
93
|
+
yield fn(t);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
117
96
|
export {
|
|
118
97
|
DefaultMap,
|
|
119
98
|
ObjectIdGenerator,
|
|
120
99
|
binarySearch,
|
|
121
100
|
chunkedArrayPush,
|
|
101
|
+
concatIterable,
|
|
122
102
|
globalObjectIdGenerator,
|
|
123
|
-
|
|
103
|
+
mapIterable
|
|
124
104
|
};
|
|
125
105
|
//# sourceMappingURL=utils.js.map
|
package/dist/esm/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["/**\n * Simple assertion function for runtime checks.\n * Throws an error if the condition is false.\n */\nexport function assert(\n condition: unknown,\n message?: string\n): asserts condition {\n if (!condition) {\n throw new Error(message || `Assertion failed`)\n }\n}\n\n/**\n * A map that returns a default value for keys that are not present.\n */\nexport class DefaultMap<K, V> extends Map<K, V> {\n constructor(\n private defaultValue: () => V,\n entries?: Iterable<[K, V]>\n ) {\n super(entries)\n }\n\n get(key: K): V {\n if (!this.has(key)) {\n // this.set(key, this.defaultValue())\n return this.defaultValue()\n }\n return super.get(key)!\n }\n\n /**\n * Update the value for a key using a function.\n */\n update(key: K, updater: (value: V) => V): V {\n const value = this.get(key)\n const newValue = updater(value)\n this.set(key, newValue)\n return newValue\n }\n}\n\n// JS engines have various limits on how many args can be passed to a function\n// with a spread operator, so we need to split the operation into chunks\n// 32767 is the max for Chrome 14, all others are higher\n// TODO: investigate the performance of this and other approaches\nconst chunkSize = 30000\nexport function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>) {\n if (other.length <= chunkSize) {\n array.push(...other)\n } else {\n for (let i = 0; i < other.length; i += chunkSize) {\n const chunk = other.slice(i, i + chunkSize)\n array.push(...chunk)\n }\n }\n}\n\nexport function binarySearch<T>(\n array: Array<T>,\n value: T,\n comparator: (a: T, b: T) => number\n): number {\n let low = 0\n let high = array.length\n while (low < high) {\n const mid = Math.floor((low + high) / 2)\n const comparison = comparator(array[mid]!, value)\n if (comparison < 0) {\n low = mid + 1\n } else if (comparison > 0) {\n high = mid\n } else {\n return mid\n }\n }\n return low\n}\n\n/**\n * Utility for generating unique IDs for objects and values.\n * Uses WeakMap for object reference tracking and consistent hashing for primitives.\n */\nexport class ObjectIdGenerator {\n private objectIds = new WeakMap<object, number>()\n private nextId = 0\n\n /**\n * Get a unique identifier for any value.\n * - Objects: Uses WeakMap for reference-based identity\n * - Primitives: Uses consistent string-based hashing\n */\n getId(value: any): number {\n // For primitives, use a simple hash of their string representation\n if (typeof value !== `object` || value === null) {\n const str = String(value)\n let hashValue = 0\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i)\n hashValue = (hashValue << 5) - hashValue + char\n hashValue = hashValue & hashValue // Convert to 32-bit integer\n }\n return hashValue\n }\n\n // For objects, use WeakMap to assign unique IDs\n if (!this.objectIds.has(value)) {\n this.objectIds.set(value, this.nextId++)\n }\n return this.objectIds.get(value)!\n }\n\n /**\n * Get a string representation of the ID for use in composite keys.\n */\n getStringId(value: any): string {\n if (value === null) return `null`\n if (value === undefined) return `undefined`\n if (typeof value !== `object`) return `str_${String(value)}`\n\n return `obj_${this.getId(value)}`\n }\n}\n\n/**\n * Global instance for cases where a shared object ID space is needed.\n */\nexport const globalObjectIdGenerator = new ObjectIdGenerator()\n\nexport function* concatIterable<T>(\n ...iterables: Array<Iterable<T>>\n): Iterable<T> {\n for (const iterable of iterables) {\n yield* iterable\n }\n}\n\nexport function* mapIterable<T, U>(\n it: Iterable<T>,\n fn: (t: T) => U\n): Iterable<U> {\n for (const t of it) {\n yield fn(t)\n }\n}\n"],"names":[],"mappings":"AAgBO,MAAM,mBAAyB,IAAU;AAAA,EAC9C,YACU,cACR,SACA;AACA,UAAM,OAAO;AAHL,SAAA,eAAA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AI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,cAAM,OAAO,IAAI,WAAW,CAAC;AAC7B,qBAAa,aAAa,KAAK,YAAY;AAC3C,oBAAY,YAAY;AAAA,MAC1B;AACA,aAAO;AAAA,IACT;AAGA,QAAI,CAAC,KAAK,UAAU,IAAI,KAAK,GAAG;AAC9B,WAAK,UAAU,IAAI,OAAO,KAAK,QAAQ;AAAA,IACzC;AACA,WAAO,KAAK,UAAU,IAAI,KAAK;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA,EAKA,YAAY,OAAoB;AAC9B,QAAI,UAAU,KAAM,QAAO;AAC3B,QAAI,UAAU,OAAW,QAAO;AAChC,QAAI,OAAO,UAAU,iBAAiB,OAAO,OAAO,KAAK,CAAC;AAE1D,WAAO,OAAO,KAAK,MAAM,KAAK,CAAC;AAAA,EACjC;AACF;AAKO,MAAM,0BAA0B,IAAI,kBAAA;AAEpC,UAAU,kBACZ,WACU;AACb,aAAW,YAAY,WAAW;AAChC,WAAO;AAAA,EACT;AACF;AAEO,UAAU,YACf,IACA,IACa;AACb,aAAW,KAAK,IAAI;AAClB,UAAM,GAAG,CAAC;AAAA,EACZ;AACF;"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A map from a difference collection trace's keys -> (value, multiplicities) that changed.
|
|
3
|
+
* Used in operations like join and reduce where the operation needs to
|
|
4
|
+
* exploit the key-value structure of the data to run efficiently.
|
|
5
|
+
*/
|
|
6
|
+
export declare class ValueIndex<K, V> {
|
|
7
|
+
#private;
|
|
8
|
+
constructor();
|
|
9
|
+
toString(indent?: boolean): string;
|
|
10
|
+
get(key: K): [V, number] | undefined;
|
|
11
|
+
getMultiplicity(key: K): number;
|
|
12
|
+
entries(): MapIterator<[K, [V, number]]>;
|
|
13
|
+
has(key: K): boolean;
|
|
14
|
+
delete(key: K): void;
|
|
15
|
+
get size(): number;
|
|
16
|
+
addValue(key: K, v: [V, number]): void;
|
|
17
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
var __typeError = (msg) => {
|
|
2
|
+
throw TypeError(msg);
|
|
3
|
+
};
|
|
4
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
5
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
6
|
+
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);
|
|
7
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
8
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
9
|
+
var _inner, _ValueIndex_instances, setMultiplicity_fn;
|
|
10
|
+
import { hash } from "./hashing/hash.js";
|
|
11
|
+
class ValueIndex {
|
|
12
|
+
// Maps key to the value and its multiplicity
|
|
13
|
+
constructor() {
|
|
14
|
+
__privateAdd(this, _ValueIndex_instances);
|
|
15
|
+
__privateAdd(this, _inner);
|
|
16
|
+
__privateSet(this, _inner, /* @__PURE__ */ new Map());
|
|
17
|
+
}
|
|
18
|
+
toString(indent = false) {
|
|
19
|
+
return `ValueIndex(${JSON.stringify(
|
|
20
|
+
[...__privateGet(this, _inner).entries()],
|
|
21
|
+
void 0,
|
|
22
|
+
indent ? 2 : void 0
|
|
23
|
+
)})`;
|
|
24
|
+
}
|
|
25
|
+
get(key) {
|
|
26
|
+
return __privateGet(this, _inner).get(key);
|
|
27
|
+
}
|
|
28
|
+
getMultiplicity(key) {
|
|
29
|
+
var _a;
|
|
30
|
+
return ((_a = this.get(key)) == null ? void 0 : _a[1]) ?? 0;
|
|
31
|
+
}
|
|
32
|
+
entries() {
|
|
33
|
+
return __privateGet(this, _inner).entries();
|
|
34
|
+
}
|
|
35
|
+
has(key) {
|
|
36
|
+
return __privateGet(this, _inner).has(key);
|
|
37
|
+
}
|
|
38
|
+
delete(key) {
|
|
39
|
+
__privateGet(this, _inner).delete(key);
|
|
40
|
+
}
|
|
41
|
+
get size() {
|
|
42
|
+
return __privateGet(this, _inner).size;
|
|
43
|
+
}
|
|
44
|
+
addValue(key, v) {
|
|
45
|
+
const [value, multiplicity] = v;
|
|
46
|
+
if (multiplicity === 0) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (this.has(key)) {
|
|
50
|
+
const [currValue, currMultiplicity] = this.get(key);
|
|
51
|
+
if (hash(value) === hash(currValue)) {
|
|
52
|
+
__privateMethod(this, _ValueIndex_instances, setMultiplicity_fn).call(this, key, value, currMultiplicity + multiplicity);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
throw new Error(
|
|
56
|
+
`Cannot add value for key ${key} because it already exists in ValueIndex with a different value`
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
__privateGet(this, _inner).set(key, [value, multiplicity]);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
_inner = new WeakMap();
|
|
63
|
+
_ValueIndex_instances = new WeakSet();
|
|
64
|
+
setMultiplicity_fn = function(key, value, multiplicity) {
|
|
65
|
+
if (multiplicity === 0) {
|
|
66
|
+
__privateGet(this, _inner).delete(key);
|
|
67
|
+
} else {
|
|
68
|
+
__privateGet(this, _inner).set(key, [value, multiplicity]);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
export {
|
|
72
|
+
ValueIndex
|
|
73
|
+
};
|
|
74
|
+
//# sourceMappingURL=valueIndex.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"valueIndex.js","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":[],"mappings":";;;;;;;;;;AAOO,MAAM,WAAiB;AAAA;AAAA,EAG5B,cAAc;AAHT;AACL;AAGE,uBAAK,4BAAa,IAAA;AAAA,EACpB;AAAA,EAEA,SAAS,SAAS,OAAe;AAC/B,WAAO,cAAc,KAAK;AAAA,MACxB,CAAC,GAAG,mBAAK,QAAO,SAAS;AAAA,MACzB;AAAA,MACA,SAAS,IAAI;AAAA,IAAA,CACd;AAAA,EACH;AAAA,EAEA,IAAI,KAAiC;AACnC,WAAO,mBAAK,QAAO,IAAI,GAAG;AAAA,EAC5B;AAAA,EAEA,gBAAgB,KAAgB;;AAC9B,aAAO,UAAK,IAAI,GAAG,MAAZ,mBAAgB,OAAM;AAAA,EAC/B;AAAA,EAEA,UAAU;AACR,WAAO,mBAAK,QAAO,QAAA;AAAA,EACrB;AAAA,EAEA,IAAI,KAAiB;AACnB,WAAO,mBAAK,QAAO,IAAI,GAAG;AAAA,EAC5B;AAAA,EAEA,OAAO,KAAc;AACnB,uBAAK,QAAO,OAAO,GAAG;AAAA,EACxB;AAAA,EAEA,IAAI,OAAe;AACjB,WAAO,mBAAK,QAAO;AAAA,EACrB;AAAA,EAEA,SAAS,KAAQ,GAAsB;AACrC,UAAM,CAAC,OAAO,YAAY,IAAI;AAE9B,QAAI,iBAAiB,GAAG;AACtB;AAAA,IACF;AAEA,QAAI,KAAK,IAAI,GAAG,GAAG;AACjB,YAAM,CAAC,WAAW,gBAAgB,IAAI,KAAK,IAAI,GAAG;AAClD,UAAI,KAAK,KAAK,MAAM,KAAK,SAAS,GAAG;AAEnC,8BAAK,2CAAL,WAAsB,KAAK,OAAO,mBAAmB;AACrD;AAAA,MACF;AAGA,YAAM,IAAI;AAAA,QACR,4BAA4B,GAAG;AAAA,MAAA;AAAA,IAEnC;AAEA,uBAAK,QAAO,IAAI,KAAK,CAAC,OAAO,YAAY,CAAC;AAAA,EAC5C;AASF;AArEE;AADK;AA+DL,qBAAA,SAAiB,KAAQ,OAAU,cAA4B;AAC7D,MAAI,iBAAiB,GAAG;AACtB,uBAAK,QAAO,OAAO,GAAG;AAAA,EACxB,OAAO;AACL,uBAAK,QAAO,IAAI,KAAK,CAAC,OAAO,YAAY,CAAC;AAAA,EAC5C;AACF;"}
|
package/package.json
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/db-ivm",
|
|
3
3
|
"description": "Incremental View Maintenance for TanStack DB based on Differential Dataflow",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.3",
|
|
5
5
|
"dependencies": {
|
|
6
6
|
"fractional-indexing": "^3.2.0",
|
|
7
|
-
"murmurhash-js": "^1.0.0",
|
|
8
7
|
"sorted-btree": "^1.8.1"
|
|
9
8
|
},
|
|
10
9
|
"devDependencies": {
|
|
11
10
|
"@types/debug": "^4.1.12",
|
|
12
|
-
"@types/murmurhash-js": "^1.0.6",
|
|
13
11
|
"@vitest/coverage-istanbul": "^3.0.9"
|
|
14
12
|
},
|
|
15
13
|
"exports": {
|
package/src/hashIndex.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { DefaultMap } from "./utils.js"
|
|
2
|
+
import { hash } from "./hashing/index.js"
|
|
3
|
+
import type { Hash } from "./hashing/index.js"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A map from a difference collection trace's keys -> (value, multiplicities) that changed.
|
|
7
|
+
* Used in operations like join and reduce where the operation needs to
|
|
8
|
+
* exploit the key-value structure of the data to run efficiently.
|
|
9
|
+
*/
|
|
10
|
+
export class HashIndex<K, V> {
|
|
11
|
+
#inner: DefaultMap<K, DefaultMap<Hash, [V, number]>>
|
|
12
|
+
|
|
13
|
+
constructor() {
|
|
14
|
+
this.#inner = new DefaultMap<K, DefaultMap<Hash, [V, number]>>(
|
|
15
|
+
() => new DefaultMap<Hash, [V, number]>(() => [undefined as any as V, 0])
|
|
16
|
+
)
|
|
17
|
+
// #inner is as map of:
|
|
18
|
+
// {
|
|
19
|
+
// [key]: {
|
|
20
|
+
// [hash(value)]: [value, multiplicity]
|
|
21
|
+
// }
|
|
22
|
+
// }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
toString(indent = false): string {
|
|
26
|
+
return `HashIndex(${JSON.stringify(
|
|
27
|
+
[...this.#inner].map(([k, valueMap]) => [k, [...valueMap]]),
|
|
28
|
+
undefined,
|
|
29
|
+
indent ? 2 : undefined
|
|
30
|
+
)})`
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
get(key: K): Array<[V, number]> {
|
|
34
|
+
const valueMap = this.#inner.get(key)
|
|
35
|
+
return [...valueMap.values()]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
getMultiplicity(key: K, value: V): number {
|
|
39
|
+
const valueMap = this.#inner.get(key)
|
|
40
|
+
const valueHash = hash(value)
|
|
41
|
+
const [, multiplicity] = valueMap.get(valueHash)
|
|
42
|
+
return multiplicity
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
entries() {
|
|
46
|
+
return this.#inner.entries()
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
*entriesIterator(): Generator<[K, [V, number]]> {
|
|
50
|
+
for (const [key, valueMap] of this.#inner.entries()) {
|
|
51
|
+
for (const [_valueHash, [value, multiplicity]] of valueMap.entries()) {
|
|
52
|
+
yield [key, [value, multiplicity]]
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
has(key: K): boolean {
|
|
58
|
+
return this.#inner.has(key)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
delete(key: K): void {
|
|
62
|
+
this.#inner.delete(key)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
get size(): number {
|
|
66
|
+
return this.#inner.size
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Adds a value to the index and does not return anything
|
|
71
|
+
* except if the addition caused the value to be removed
|
|
72
|
+
* and the key to be left with only a single value.
|
|
73
|
+
* In that case, we return the single remaining value.
|
|
74
|
+
*/
|
|
75
|
+
addValue(key: K, value: [V, number]): [V, number] | void {
|
|
76
|
+
const [val, multiplicity] = value
|
|
77
|
+
const valueMap = this.#inner.get(key)
|
|
78
|
+
const valueHash = hash(val)
|
|
79
|
+
const [, existingMultiplicity] = valueMap.get(valueHash)
|
|
80
|
+
const newMultiplicity = existingMultiplicity + multiplicity
|
|
81
|
+
if (multiplicity !== 0) {
|
|
82
|
+
if (newMultiplicity === 0) {
|
|
83
|
+
valueMap.delete(valueHash)
|
|
84
|
+
if (valueMap.size === 1) {
|
|
85
|
+
// Signal that the key only has a single remaining value
|
|
86
|
+
return valueMap.entries().next().value![1]
|
|
87
|
+
}
|
|
88
|
+
} else {
|
|
89
|
+
valueMap.set(valueHash, [val, newMultiplicity])
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
this.#inner.set(key, valueMap)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { MurmurHashStream, randomHash } from "./murmur.js"
|
|
2
|
+
import type { Hasher } from "./murmur.js"
|
|
3
|
+
|
|
4
|
+
/*
|
|
5
|
+
* Implementation of structural hashing based on the Composites polyfill implementation:
|
|
6
|
+
* https://github.com/tc39/proposal-composites
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const TRUE = randomHash()
|
|
10
|
+
const FALSE = randomHash()
|
|
11
|
+
const NULL = randomHash()
|
|
12
|
+
const UNDEFINED = randomHash()
|
|
13
|
+
const KEY = randomHash()
|
|
14
|
+
const FUNCTIONS = randomHash()
|
|
15
|
+
const DATE_MARKER = randomHash()
|
|
16
|
+
const OBJECT_MARKER = randomHash()
|
|
17
|
+
const ARRAY_MARKER = randomHash()
|
|
18
|
+
const MAP_MARKER = randomHash()
|
|
19
|
+
const SET_MARKER = randomHash()
|
|
20
|
+
|
|
21
|
+
const hashCache = new WeakMap<object, number>()
|
|
22
|
+
|
|
23
|
+
export function hash(input: any): number {
|
|
24
|
+
const hasher = new MurmurHashStream()
|
|
25
|
+
updateHasher(hasher, input)
|
|
26
|
+
return hasher.digest()
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function hashObject(input: object): number {
|
|
30
|
+
const cachedHash = hashCache.get(input)
|
|
31
|
+
if (cachedHash !== undefined) {
|
|
32
|
+
return cachedHash
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
let valueHash: number | undefined
|
|
36
|
+
if (input instanceof Date) {
|
|
37
|
+
valueHash = hashDate(input)
|
|
38
|
+
} else {
|
|
39
|
+
let plainObjectInput = input
|
|
40
|
+
let marker = OBJECT_MARKER
|
|
41
|
+
|
|
42
|
+
if (input instanceof Array) {
|
|
43
|
+
marker = ARRAY_MARKER
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (input instanceof Map) {
|
|
47
|
+
marker = MAP_MARKER
|
|
48
|
+
plainObjectInput = [...input.entries()]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (input instanceof Set) {
|
|
52
|
+
marker = SET_MARKER
|
|
53
|
+
plainObjectInput = [...input.entries()]
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (
|
|
57
|
+
input instanceof Buffer ||
|
|
58
|
+
input instanceof Uint8Array ||
|
|
59
|
+
input instanceof File
|
|
60
|
+
) {
|
|
61
|
+
// Deeply hashing these objects would be too costly
|
|
62
|
+
// but we also don't want to ignore them
|
|
63
|
+
// so we track them by reference and cache them in a weak map
|
|
64
|
+
return cachedReferenceHash(input)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
valueHash = hashPlainObject(plainObjectInput, marker)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
hashCache.set(input, valueHash)
|
|
71
|
+
return valueHash
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function hashDate(input: Date): number {
|
|
75
|
+
const hasher = new MurmurHashStream()
|
|
76
|
+
hasher.update(DATE_MARKER)
|
|
77
|
+
hasher.update(input.getTime())
|
|
78
|
+
return hasher.digest()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function hashPlainObject(input: object, marker: number): number {
|
|
82
|
+
const hasher = new MurmurHashStream()
|
|
83
|
+
|
|
84
|
+
// Mark the type of the input
|
|
85
|
+
hasher.update(marker)
|
|
86
|
+
const keys = Object.keys(input)
|
|
87
|
+
keys.sort(keySort)
|
|
88
|
+
for (const key of keys) {
|
|
89
|
+
hasher.update(KEY)
|
|
90
|
+
hasher.update(key)
|
|
91
|
+
updateHasher(hasher, input[key as keyof typeof input])
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return hasher.digest()
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function updateHasher(hasher: Hasher, input: unknown): void {
|
|
98
|
+
if (input === null) {
|
|
99
|
+
hasher.update(NULL)
|
|
100
|
+
return
|
|
101
|
+
}
|
|
102
|
+
switch (typeof input) {
|
|
103
|
+
case `undefined`:
|
|
104
|
+
hasher.update(UNDEFINED)
|
|
105
|
+
return
|
|
106
|
+
case `boolean`:
|
|
107
|
+
hasher.update(input ? TRUE : FALSE)
|
|
108
|
+
return
|
|
109
|
+
case `number`:
|
|
110
|
+
// Normalize NaNs and -0
|
|
111
|
+
hasher.update(isNaN(input) ? NaN : input === 0 ? 0 : input)
|
|
112
|
+
return
|
|
113
|
+
case `bigint`:
|
|
114
|
+
case `string`:
|
|
115
|
+
case `symbol`:
|
|
116
|
+
hasher.update(input)
|
|
117
|
+
return
|
|
118
|
+
case `object`:
|
|
119
|
+
hasher.update(getCachedHash(input))
|
|
120
|
+
return
|
|
121
|
+
case `function`:
|
|
122
|
+
// Functions are assigned a globally unique ID
|
|
123
|
+
// and that ID is cached in the weak map
|
|
124
|
+
hasher.update(cachedReferenceHash(input))
|
|
125
|
+
return
|
|
126
|
+
default:
|
|
127
|
+
console.warn(
|
|
128
|
+
`Ignored input during hashing because it is of type ${typeof input} which is not supported`
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function getCachedHash(input: object): number {
|
|
134
|
+
let valueHash = hashCache.get(input)
|
|
135
|
+
if (valueHash === undefined) {
|
|
136
|
+
valueHash = hashObject(input)
|
|
137
|
+
}
|
|
138
|
+
return valueHash
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
let nextRefId = 1
|
|
142
|
+
function cachedReferenceHash(fn: object): number {
|
|
143
|
+
let valueHash = hashCache.get(fn)
|
|
144
|
+
if (valueHash === undefined) {
|
|
145
|
+
valueHash = nextRefId ^ FUNCTIONS
|
|
146
|
+
nextRefId++
|
|
147
|
+
hashCache.set(fn, valueHash)
|
|
148
|
+
}
|
|
149
|
+
return valueHash
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Strings sorted lexicographically.
|
|
154
|
+
*/
|
|
155
|
+
function keySort(a: string, b: string): number {
|
|
156
|
+
return a.localeCompare(b)
|
|
157
|
+
}
|