@tanstack/db-ivm 0.1.7 → 0.1.9
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/indexes.cjs +243 -85
- package/dist/cjs/indexes.cjs.map +1 -1
- package/dist/cjs/indexes.d.cts +58 -7
- package/dist/cjs/operators/distinct.cjs +2 -2
- package/dist/cjs/operators/distinct.cjs.map +1 -1
- package/dist/cjs/operators/distinct.d.cts +6 -4
- package/dist/cjs/operators/groupBy.cjs +12 -10
- package/dist/cjs/operators/groupBy.cjs.map +1 -1
- package/dist/cjs/operators/groupBy.d.cts +7 -4
- package/dist/cjs/utils.cjs +0 -12
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/esm/indexes.d.ts +58 -7
- package/dist/esm/indexes.js +243 -85
- package/dist/esm/indexes.js.map +1 -1
- package/dist/esm/operators/distinct.d.ts +6 -4
- package/dist/esm/operators/distinct.js +2 -2
- package/dist/esm/operators/distinct.js.map +1 -1
- package/dist/esm/operators/groupBy.d.ts +7 -4
- package/dist/esm/operators/groupBy.js +12 -10
- package/dist/esm/operators/groupBy.js.map +1 -1
- package/dist/esm/utils.js +1 -13
- package/dist/esm/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/indexes.ts +365 -90
- package/src/operators/distinct.ts +13 -8
- package/src/operators/groupBy.ts +38 -18
- package/dist/cjs/hashIndex.cjs +0 -83
- package/dist/cjs/hashIndex.cjs.map +0 -1
- package/dist/cjs/hashIndex.d.cts +0 -25
- package/dist/cjs/valueIndex.cjs +0 -74
- package/dist/cjs/valueIndex.cjs.map +0 -1
- package/dist/cjs/valueIndex.d.cts +0 -17
- package/dist/esm/hashIndex.d.ts +0 -25
- package/dist/esm/hashIndex.js +0 -83
- package/dist/esm/hashIndex.js.map +0 -1
- package/dist/esm/valueIndex.d.ts +0 -17
- package/dist/esm/valueIndex.js +0 -74
- package/dist/esm/valueIndex.js.map +0 -1
- package/src/hashIndex.ts +0 -94
- package/src/valueIndex.ts +0 -78
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupBy.cjs","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":["map","reduce"],"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/BA,IAAAA,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;AAIH,UAAM,UAAU,kBAAkB;AAAA,MAChCC,OAAAA,OAAO,CAAC,WAAW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,CAAC,WAAiD;AAExD,YAAM,kCAAkB,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.cjs","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\ntype CanMinMax = number | Date | bigint\n\n/**\n * Creates a min aggregate function that computes the minimum value in a group\n * @param valueExtractor Function to extract a comparable value from each data entry\n */\nexport function min<T extends CanMinMax>(): AggregateFunction<\n T,\n T | undefined,\n T | undefined\n>\nexport function min<T, V extends CanMinMax>(\n valueExtractor: (value: T) => V\n): AggregateFunction<T, V | undefined, V | undefined>\nexport function min<T, V extends CanMinMax>(\n valueExtractor?: (value: T) => V\n): AggregateFunction<T, V | undefined, V | undefined> {\n const extractor = valueExtractor ?? ((v: T) => v as unknown as V)\n return {\n preMap: (data: T) => extractor(data),\n reduce: (values) => {\n let minValue: V | undefined\n for (const [value, _multiplicity] of values) {\n if (!minValue || (value && value < minValue)) {\n minValue = value\n }\n }\n return 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 comparable value from each data entry\n */\nexport function max<T extends CanMinMax>(): AggregateFunction<\n T,\n T | undefined,\n T | undefined\n>\nexport function max<T, V extends CanMinMax>(\n valueExtractor: (value: T) => V\n): AggregateFunction<T, V | undefined, V | undefined>\nexport function max<T, V extends CanMinMax>(\n valueExtractor?: (value: T) => V\n): AggregateFunction<T, V | undefined, V | undefined> {\n const extractor = valueExtractor ?? ((v: T) => v as unknown as V)\n return {\n preMap: (data: T) => extractor(data),\n reduce: (values) => {\n let maxValue: V | undefined\n for (const [value, _multiplicity] of values) {\n if (!maxValue || (value && value > maxValue)) {\n maxValue = value\n }\n }\n return 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 av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AG,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;;;;;;;;;;"}
|
|
@@ -34,16 +34,19 @@ export declare function avg<T>(valueExtractor?: (value: T) => number): Aggregate
|
|
|
34
34
|
sum: number;
|
|
35
35
|
count: number;
|
|
36
36
|
}>;
|
|
37
|
+
type CanMinMax = number | Date | bigint;
|
|
37
38
|
/**
|
|
38
39
|
* Creates a min aggregate function that computes the minimum value in a group
|
|
39
|
-
* @param valueExtractor Function to extract a
|
|
40
|
+
* @param valueExtractor Function to extract a comparable value from each data entry
|
|
40
41
|
*/
|
|
41
|
-
export declare function min<T>(
|
|
42
|
+
export declare function min<T extends CanMinMax>(): AggregateFunction<T, T | undefined, T | undefined>;
|
|
43
|
+
export declare function min<T, V extends CanMinMax>(valueExtractor: (value: T) => V): AggregateFunction<T, V | undefined, V | undefined>;
|
|
42
44
|
/**
|
|
43
45
|
* Creates a max aggregate function that computes the maximum value in a group
|
|
44
|
-
* @param valueExtractor Function to extract a
|
|
46
|
+
* @param valueExtractor Function to extract a comparable value from each data entry
|
|
45
47
|
*/
|
|
46
|
-
export declare function max<T>(
|
|
48
|
+
export declare function max<T extends CanMinMax>(): AggregateFunction<T, T | undefined, T | undefined>;
|
|
49
|
+
export declare function max<T, V extends CanMinMax>(valueExtractor: (value: T) => V): AggregateFunction<T, V | undefined, V | undefined>;
|
|
47
50
|
/**
|
|
48
51
|
* Creates a median aggregate function that computes the middle value in a sorted group
|
|
49
52
|
* If there's an even number of values, returns the average of the two middle values
|
package/dist/cjs/utils.cjs
CHANGED
|
@@ -85,21 +85,9 @@ class ObjectIdGenerator {
|
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
87
|
const globalObjectIdGenerator = new ObjectIdGenerator();
|
|
88
|
-
function* concatIterable(...iterables) {
|
|
89
|
-
for (const iterable of iterables) {
|
|
90
|
-
yield* iterable;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
function* mapIterable(it, fn) {
|
|
94
|
-
for (const t of it) {
|
|
95
|
-
yield fn(t);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
88
|
exports.DefaultMap = DefaultMap;
|
|
99
89
|
exports.ObjectIdGenerator = ObjectIdGenerator;
|
|
100
90
|
exports.binarySearch = binarySearch;
|
|
101
91
|
exports.chunkedArrayPush = chunkedArrayPush;
|
|
102
|
-
exports.concatIterable = concatIterable;
|
|
103
92
|
exports.globalObjectIdGenerator = globalObjectIdGenerator;
|
|
104
|
-
exports.mapIterable = mapIterable;
|
|
105
93
|
//# sourceMappingURL=utils.cjs.map
|
package/dist/cjs/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","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;AAAA,EAIV;AAAA,EAEA,IAAI,KAAW;AACb,QAAI,CAAC,KAAK,IAAI,GAAG,GAAG;AAElB,aAAO,KAAK,aAAA;AAAA,IACd;AACA,WAAO,MAAM,IAAI,GAAG;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,KAAQ,SAA6B;AAC1C,UAAM,QAAQ,KAAK,IAAI,GAAG;AAC1B,UAAM,WAAW,QAAQ,KAAK;AAC9B,SAAK,IAAI,KAAK,QAAQ;AACtB,WAAO;AAAA,EACT;AACF;AAMA,MAAM,YAAY;AACX,SAAS,iBAAiB,OAAuB,OAAuB;AAC7E,MAAI,MAAM,UAAU,WAAW;AAC7B,UAAM,KAAK,GAAG,KAAK;AAAA,EACrB,OAAO;AACL,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;AAChD,YAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,SAAS;AAC1C,YAAM,KAAK,GAAG,KAAK;AAAA,IACrB;AAAA,EACF;AACF;AAEO,SAAS,aACd,OACA,OACA,YACQ;AACR,MAAI,MAAM;AACV,MAAI,OAAO,MAAM;AACjB,SAAO,MAAM,MAAM;AACjB,UAAM,MAAM,KAAK,OAAO,MAAM,QAAQ,CAAC;AACvC,UAAM,aAAa,WAAW,MAAM,GAAG,GAAI,KAAK;AAChD,QAAI,aAAa,GAAG;AAClB,YAAM,MAAM;AAAA,IACd,WAAW,aAAa,GAAG;AACzB,aAAO;AAAA,IACT,OAAO;AACL,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAMO,MAAM,kBAAkB;AAAA,EAAxB,cAAA;AACL,SAAQ,gCAAgB,QAAA;AACxB,SAAQ,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOjB,MAAM,OAAoB;AAExB,QAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAC/C,YAAM,MAAM,OAAO,KAAK;AACxB,UAAI,YAAY;AAChB,eAAS,IAAI,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
|
|
1
|
+
{"version":3,"file":"utils.cjs","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;AAAA,EAIV;AAAA,EAEA,IAAI,KAAW;AACb,QAAI,CAAC,KAAK,IAAI,GAAG,GAAG;AAElB,aAAO,KAAK,aAAA;AAAA,IACd;AACA,WAAO,MAAM,IAAI,GAAG;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,KAAQ,SAA6B;AAC1C,UAAM,QAAQ,KAAK,IAAI,GAAG;AAC1B,UAAM,WAAW,QAAQ,KAAK;AAC9B,SAAK,IAAI,KAAK,QAAQ;AACtB,WAAO;AAAA,EACT;AACF;AAMA,MAAM,YAAY;AACX,SAAS,iBAAiB,OAAuB,OAAuB;AAC7E,MAAI,MAAM,UAAU,WAAW;AAC7B,UAAM,KAAK,GAAG,KAAK;AAAA,EACrB,OAAO;AACL,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;AAChD,YAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,SAAS;AAC1C,YAAM,KAAK,GAAG,KAAK;AAAA,IACrB;AAAA,EACF;AACF;AAEO,SAAS,aACd,OACA,OACA,YACQ;AACR,MAAI,MAAM;AACV,MAAI,OAAO,MAAM;AACjB,SAAO,MAAM,MAAM;AACjB,UAAM,MAAM,KAAK,OAAO,MAAM,QAAQ,CAAC;AACvC,UAAM,aAAa,WAAW,MAAM,GAAG,GAAI,KAAK;AAChD,QAAI,aAAa,GAAG;AAClB,YAAM,MAAM;AAAA,IACd,WAAW,aAAa,GAAG;AACzB,aAAO;AAAA,IACT,OAAO;AACL,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAMO,MAAM,kBAAkB;AAAA,EAAxB,cAAA;AACL,SAAQ,gCAAgB,QAAA;AACxB,SAAQ,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOjB,MAAM,OAAoB;AAExB,QAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAC/C,YAAM,MAAM,OAAO,KAAK;AACxB,UAAI,YAAY;AAChB,eAAS,IAAI,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;;;;;;"}
|
package/dist/esm/indexes.d.ts
CHANGED
|
@@ -1,18 +1,69 @@
|
|
|
1
1
|
import { MultiSet } from './multiset.js';
|
|
2
|
+
type SingleValue<TValue> = [TValue, number];
|
|
2
3
|
/**
|
|
3
4
|
* A map from a difference collection trace's keys -> (value, multiplicities) that changed.
|
|
4
5
|
* Used in operations like join and reduce where the operation needs to
|
|
5
6
|
* exploit the key-value structure of the data to run efficiently.
|
|
6
7
|
*/
|
|
7
|
-
export declare class Index<
|
|
8
|
+
export declare class Index<TKey, TValue, TPrefix = any> {
|
|
8
9
|
#private;
|
|
9
10
|
constructor();
|
|
11
|
+
/**
|
|
12
|
+
* This method returns a string representation of the index.
|
|
13
|
+
* @param indent - Whether to indent the string representation.
|
|
14
|
+
* @returns A string representation of the index.
|
|
15
|
+
*/
|
|
10
16
|
toString(indent?: boolean): string;
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
17
|
+
/**
|
|
18
|
+
* The size of the index.
|
|
19
|
+
*/
|
|
14
20
|
get size(): number;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
21
|
+
/**
|
|
22
|
+
* This method checks if the index has a given key.
|
|
23
|
+
* @param key - The key to check.
|
|
24
|
+
* @returns True if the index has the key, false otherwise.
|
|
25
|
+
*/
|
|
26
|
+
has(key: TKey): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* This method returns all values for a given key.
|
|
29
|
+
* @param key - The key to get the values for.
|
|
30
|
+
* @returns An array of value tuples [value, multiplicity].
|
|
31
|
+
*/
|
|
32
|
+
get(key: TKey): Array<[TValue, number]>;
|
|
33
|
+
/**
|
|
34
|
+
* This method returns an iterator over all values for a given key.
|
|
35
|
+
* @param key - The key to get the values for.
|
|
36
|
+
* @returns An iterator of value tuples [value, multiplicity].
|
|
37
|
+
*/
|
|
38
|
+
getIterator(key: TKey): Iterable<[TValue, number]>;
|
|
39
|
+
/**
|
|
40
|
+
* This returns an iterator that iterates over all key-value pairs.
|
|
41
|
+
* @returns An iterable of all key-value pairs (and their multiplicities) in the index.
|
|
42
|
+
*/
|
|
43
|
+
entries(): Iterable<[TKey, [TValue, number]]>;
|
|
44
|
+
/**
|
|
45
|
+
* This method only iterates over the keys and not over the values.
|
|
46
|
+
* Hence, it is more efficient than the `#entries` method.
|
|
47
|
+
* It returns an iterator that you can use if you need to iterate over the values for a given key.
|
|
48
|
+
* @returns An iterator of all *keys* in the index and their corresponding value iterator.
|
|
49
|
+
*/
|
|
50
|
+
entriesIterators(): Iterable<[TKey, Iterable<[TValue, number]>]>;
|
|
51
|
+
/**
|
|
52
|
+
* This method adds a value to the index.
|
|
53
|
+
* @param key - The key to add the value to.
|
|
54
|
+
* @param valueTuple - The value tuple [value, multiplicity] to add to the index.
|
|
55
|
+
*/
|
|
56
|
+
addValue(key: TKey, valueTuple: SingleValue<TValue>): void;
|
|
57
|
+
/**
|
|
58
|
+
* This method appends another index to the current index.
|
|
59
|
+
* @param other - The index to append to the current index.
|
|
60
|
+
*/
|
|
61
|
+
append(other: Index<TKey, TValue>): void;
|
|
62
|
+
/**
|
|
63
|
+
* This method joins two indexes.
|
|
64
|
+
* @param other - The index to join with the current index.
|
|
65
|
+
* @returns A multiset of the joined values.
|
|
66
|
+
*/
|
|
67
|
+
join<TValue2>(other: Index<TKey, TValue2>): MultiSet<[TKey, [TValue, TValue2]]>;
|
|
18
68
|
}
|
|
69
|
+
export {};
|
package/dist/esm/indexes.js
CHANGED
|
@@ -6,97 +6,227 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
|
|
|
6
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
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
8
|
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
9
|
-
var
|
|
9
|
+
var _inner, _Index_instances, handleSingleValueTransition_fn;
|
|
10
10
|
import { MultiSet } from "./multiset.js";
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
11
|
+
import { hash } from "./hashing/hash.js";
|
|
12
|
+
const NO_PREFIX = Symbol(`NO_PREFIX`);
|
|
13
|
+
class PrefixMap extends Map {
|
|
14
|
+
/**
|
|
15
|
+
* Add a value to the PrefixMap. Returns true if the map becomes empty after the operation.
|
|
16
|
+
*/
|
|
17
|
+
addValue(value, multiplicity) {
|
|
18
|
+
if (multiplicity === 0) return this.size === 0;
|
|
19
|
+
const prefix = getPrefix(value);
|
|
20
|
+
const valueMapOrSingleValue = this.get(prefix);
|
|
21
|
+
if (isSingleValue(valueMapOrSingleValue)) {
|
|
22
|
+
const [currentValue, currentMultiplicity] = valueMapOrSingleValue;
|
|
23
|
+
const currentPrefix = getPrefix(currentValue);
|
|
24
|
+
if (currentPrefix !== prefix) {
|
|
25
|
+
throw new Error(`Mismatching prefixes, this should never happen`);
|
|
26
|
+
}
|
|
27
|
+
if (currentValue === value || hash(currentValue) === hash(value)) {
|
|
28
|
+
const newMultiplicity = currentMultiplicity + multiplicity;
|
|
29
|
+
if (newMultiplicity === 0) {
|
|
30
|
+
this.delete(prefix);
|
|
31
|
+
} else {
|
|
32
|
+
this.set(prefix, [value, newMultiplicity]);
|
|
33
|
+
}
|
|
34
|
+
} else {
|
|
35
|
+
const valueMap = new ValueMap();
|
|
36
|
+
valueMap.set(hash(currentValue), valueMapOrSingleValue);
|
|
37
|
+
valueMap.set(hash(value), [value, multiplicity]);
|
|
38
|
+
this.set(prefix, valueMap);
|
|
39
|
+
}
|
|
40
|
+
} else if (valueMapOrSingleValue === void 0) {
|
|
41
|
+
this.set(prefix, [value, multiplicity]);
|
|
42
|
+
} else {
|
|
43
|
+
const isEmpty = valueMapOrSingleValue.addValue(value, multiplicity);
|
|
44
|
+
if (isEmpty) {
|
|
45
|
+
this.delete(prefix);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return this.size === 0;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
class ValueMap extends Map {
|
|
52
|
+
/**
|
|
53
|
+
* Add a value to the ValueMap. Returns true if the map becomes empty after the operation.
|
|
54
|
+
* @param value - The full value to store
|
|
55
|
+
* @param multiplicity - The multiplicity to add
|
|
56
|
+
* @param hashKey - Optional hash key to use instead of hashing the full value (used when in PrefixMap context)
|
|
57
|
+
*/
|
|
58
|
+
addValue(value, multiplicity) {
|
|
59
|
+
if (multiplicity === 0) return this.size === 0;
|
|
60
|
+
const key = hash(value);
|
|
61
|
+
const currentValue = this.get(key);
|
|
62
|
+
if (currentValue) {
|
|
63
|
+
const [, currentMultiplicity] = currentValue;
|
|
64
|
+
const newMultiplicity = currentMultiplicity + multiplicity;
|
|
65
|
+
if (newMultiplicity === 0) {
|
|
66
|
+
this.delete(key);
|
|
67
|
+
} else {
|
|
68
|
+
this.set(key, [value, newMultiplicity]);
|
|
69
|
+
}
|
|
70
|
+
} else {
|
|
71
|
+
this.set(key, [value, multiplicity]);
|
|
72
|
+
}
|
|
73
|
+
return this.size === 0;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
14
76
|
class Index {
|
|
15
77
|
constructor() {
|
|
16
78
|
__privateAdd(this, _Index_instances);
|
|
17
79
|
/*
|
|
18
|
-
* This
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* it is added to the `hashIndex` and removed from the `valueIndex` and vice versa.
|
|
80
|
+
* This index maintains a nested map of keys -> (value, multiplicities), where:
|
|
81
|
+
* - initially the values are stored against the key as a single value tuple
|
|
82
|
+
* - when a key gets additional values, the values are stored against the key in a
|
|
83
|
+
* prefix map
|
|
84
|
+
* - the prefix is extract where possible from values that are structured as
|
|
85
|
+
* [rowPrimaryKey, rowValue], as they are in the Tanstack DB query pipeline.
|
|
86
|
+
* - only when there are multiple values for a given prefix do we fall back to a
|
|
87
|
+
* hash to identify identical values, storing them in a third level value map.
|
|
27
88
|
*/
|
|
28
|
-
__privateAdd(this,
|
|
29
|
-
|
|
30
|
-
__privateSet(this, _valueIndex, new ValueIndex());
|
|
31
|
-
__privateSet(this, _hashIndex, new HashIndex());
|
|
89
|
+
__privateAdd(this, _inner);
|
|
90
|
+
__privateSet(this, _inner, /* @__PURE__ */ new Map());
|
|
32
91
|
}
|
|
92
|
+
/**
|
|
93
|
+
* This method returns a string representation of the index.
|
|
94
|
+
* @param indent - Whether to indent the string representation.
|
|
95
|
+
* @returns A string representation of the index.
|
|
96
|
+
*/
|
|
33
97
|
toString(indent = false) {
|
|
34
|
-
return `Index(
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
98
|
+
return `Index(${JSON.stringify(
|
|
99
|
+
[...this.entries()],
|
|
100
|
+
void 0,
|
|
101
|
+
indent ? 2 : void 0
|
|
102
|
+
)})`;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* The size of the index.
|
|
106
|
+
*/
|
|
107
|
+
get size() {
|
|
108
|
+
return __privateGet(this, _inner).size;
|
|
38
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* This method checks if the index has a given key.
|
|
112
|
+
* @param key - The key to check.
|
|
113
|
+
* @returns True if the index has the key, false otherwise.
|
|
114
|
+
*/
|
|
115
|
+
has(key) {
|
|
116
|
+
return __privateGet(this, _inner).has(key);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* This method returns all values for a given key.
|
|
120
|
+
* @param key - The key to get the values for.
|
|
121
|
+
* @returns An array of value tuples [value, multiplicity].
|
|
122
|
+
*/
|
|
39
123
|
get(key) {
|
|
40
|
-
|
|
41
|
-
return [__privateGet(this, _valueIndex).get(key)];
|
|
42
|
-
}
|
|
43
|
-
return __privateGet(this, _hashIndex).get(key);
|
|
124
|
+
return [...this.getIterator(key)];
|
|
44
125
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
126
|
+
/**
|
|
127
|
+
* This method returns an iterator over all values for a given key.
|
|
128
|
+
* @param key - The key to get the values for.
|
|
129
|
+
* @returns An iterator of value tuples [value, multiplicity].
|
|
130
|
+
*/
|
|
131
|
+
*getIterator(key) {
|
|
132
|
+
const mapOrSingleValue = __privateGet(this, _inner).get(key);
|
|
133
|
+
if (isSingleValue(mapOrSingleValue)) {
|
|
134
|
+
yield mapOrSingleValue;
|
|
135
|
+
} else if (mapOrSingleValue === void 0) {
|
|
136
|
+
return;
|
|
137
|
+
} else if (mapOrSingleValue instanceof ValueMap) {
|
|
138
|
+
for (const valueTuple of mapOrSingleValue.values()) {
|
|
139
|
+
yield valueTuple;
|
|
140
|
+
}
|
|
141
|
+
} else {
|
|
142
|
+
for (const singleValueOrValueMap of mapOrSingleValue.values()) {
|
|
143
|
+
if (isSingleValue(singleValueOrValueMap)) {
|
|
144
|
+
yield singleValueOrValueMap;
|
|
145
|
+
} else {
|
|
146
|
+
for (const valueTuple of singleValueOrValueMap.values()) {
|
|
147
|
+
yield valueTuple;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
48
151
|
}
|
|
49
|
-
return __privateGet(this, _hashIndex).getMultiplicity(key, value);
|
|
50
152
|
}
|
|
51
|
-
|
|
52
|
-
|
|
153
|
+
/**
|
|
154
|
+
* This returns an iterator that iterates over all key-value pairs.
|
|
155
|
+
* @returns An iterable of all key-value pairs (and their multiplicities) in the index.
|
|
156
|
+
*/
|
|
157
|
+
*entries() {
|
|
158
|
+
for (const key of __privateGet(this, _inner).keys()) {
|
|
159
|
+
for (const valueTuple of this.getIterator(key)) {
|
|
160
|
+
yield [key, valueTuple];
|
|
161
|
+
}
|
|
162
|
+
}
|
|
53
163
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
);
|
|
164
|
+
/**
|
|
165
|
+
* This method only iterates over the keys and not over the values.
|
|
166
|
+
* Hence, it is more efficient than the `#entries` method.
|
|
167
|
+
* It returns an iterator that you can use if you need to iterate over the values for a given key.
|
|
168
|
+
* @returns An iterator of all *keys* in the index and their corresponding value iterator.
|
|
169
|
+
*/
|
|
170
|
+
*entriesIterators() {
|
|
171
|
+
for (const key of __privateGet(this, _inner).keys()) {
|
|
172
|
+
yield [key, this.getIterator(key)];
|
|
64
173
|
}
|
|
65
|
-
|
|
66
|
-
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* This method adds a value to the index.
|
|
177
|
+
* @param key - The key to add the value to.
|
|
178
|
+
* @param valueTuple - The value tuple [value, multiplicity] to add to the index.
|
|
179
|
+
*/
|
|
180
|
+
addValue(key, valueTuple) {
|
|
181
|
+
const [value, multiplicity] = valueTuple;
|
|
182
|
+
if (multiplicity === 0) return;
|
|
183
|
+
const mapOrSingleValue = __privateGet(this, _inner).get(key);
|
|
184
|
+
if (mapOrSingleValue === void 0) {
|
|
185
|
+
__privateGet(this, _inner).set(key, valueTuple);
|
|
67
186
|
return;
|
|
68
187
|
}
|
|
69
|
-
if (
|
|
70
|
-
|
|
71
|
-
__privateGet(this, _valueIndex).addValue(key, value);
|
|
72
|
-
} catch {
|
|
73
|
-
const existingValue = __privateGet(this, _valueIndex).get(key);
|
|
74
|
-
__privateGet(this, _valueIndex).delete(key);
|
|
75
|
-
__privateGet(this, _hashIndex).addValue(key, existingValue);
|
|
76
|
-
__privateGet(this, _hashIndex).addValue(key, value);
|
|
77
|
-
}
|
|
188
|
+
if (isSingleValue(mapOrSingleValue)) {
|
|
189
|
+
__privateMethod(this, _Index_instances, handleSingleValueTransition_fn).call(this, key, mapOrSingleValue, value, multiplicity);
|
|
78
190
|
return;
|
|
79
191
|
}
|
|
80
|
-
if (
|
|
81
|
-
const
|
|
82
|
-
if (
|
|
83
|
-
|
|
84
|
-
|
|
192
|
+
if (mapOrSingleValue instanceof ValueMap) {
|
|
193
|
+
const prefix = getPrefix(value);
|
|
194
|
+
if (prefix !== NO_PREFIX) {
|
|
195
|
+
const prefixMap = new PrefixMap();
|
|
196
|
+
prefixMap.set(NO_PREFIX, mapOrSingleValue);
|
|
197
|
+
prefixMap.set(prefix, valueTuple);
|
|
198
|
+
__privateGet(this, _inner).set(key, prefixMap);
|
|
199
|
+
} else {
|
|
200
|
+
const isEmpty = mapOrSingleValue.addValue(value, multiplicity);
|
|
201
|
+
if (isEmpty) {
|
|
202
|
+
__privateGet(this, _inner).delete(key);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
} else {
|
|
206
|
+
const isEmpty = mapOrSingleValue.addValue(value, multiplicity);
|
|
207
|
+
if (isEmpty) {
|
|
208
|
+
__privateGet(this, _inner).delete(key);
|
|
85
209
|
}
|
|
86
|
-
return;
|
|
87
210
|
}
|
|
88
211
|
}
|
|
212
|
+
/**
|
|
213
|
+
* This method appends another index to the current index.
|
|
214
|
+
* @param other - The index to append to the current index.
|
|
215
|
+
*/
|
|
89
216
|
append(other) {
|
|
90
|
-
|
|
91
|
-
for (const [key, value] of __privateMethod(_a = other, _Index_instances, entries_fn).call(_a)) {
|
|
217
|
+
for (const [key, value] of other.entries()) {
|
|
92
218
|
this.addValue(key, value);
|
|
93
219
|
}
|
|
94
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* This method joins two indexes.
|
|
223
|
+
* @param other - The index to join with the current index.
|
|
224
|
+
* @returns A multiset of the joined values.
|
|
225
|
+
*/
|
|
95
226
|
join(other) {
|
|
96
|
-
var _a;
|
|
97
227
|
const result = [];
|
|
98
228
|
if (this.size <= other.size) {
|
|
99
|
-
for (const [key, valueIt] of
|
|
229
|
+
for (const [key, valueIt] of this.entriesIterators()) {
|
|
100
230
|
if (!other.has(key)) continue;
|
|
101
231
|
const otherValues = other.get(key);
|
|
102
232
|
for (const [val1, mul1] of valueIt) {
|
|
@@ -108,7 +238,7 @@ class Index {
|
|
|
108
238
|
}
|
|
109
239
|
}
|
|
110
240
|
} else {
|
|
111
|
-
for (const [key, otherValueIt] of
|
|
241
|
+
for (const [key, otherValueIt] of other.entriesIterators()) {
|
|
112
242
|
if (!this.has(key)) continue;
|
|
113
243
|
const values = this.get(key);
|
|
114
244
|
for (const [val2, mul2] of otherValueIt) {
|
|
@@ -123,33 +253,61 @@ class Index {
|
|
|
123
253
|
return new MultiSet(result);
|
|
124
254
|
}
|
|
125
255
|
}
|
|
126
|
-
|
|
127
|
-
_hashIndex = new WeakMap();
|
|
256
|
+
_inner = new WeakMap();
|
|
128
257
|
_Index_instances = new WeakSet();
|
|
129
258
|
/**
|
|
130
|
-
*
|
|
131
|
-
* @returns An iterable of all key-value pairs (and their multiplicities) in the index.
|
|
259
|
+
* Handle the transition from a single value to either a ValueMap or PrefixMap
|
|
132
260
|
*/
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
261
|
+
handleSingleValueTransition_fn = function(key, currentSingleValue, newValue, multiplicity) {
|
|
262
|
+
const [currentValue, currentMultiplicity] = currentSingleValue;
|
|
263
|
+
if (currentValue === newValue) {
|
|
264
|
+
const newMultiplicity = currentMultiplicity + multiplicity;
|
|
265
|
+
if (newMultiplicity === 0) {
|
|
266
|
+
__privateGet(this, _inner).delete(key);
|
|
267
|
+
} else {
|
|
268
|
+
__privateGet(this, _inner).set(key, [newValue, newMultiplicity]);
|
|
269
|
+
}
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const newPrefix = getPrefix(newValue);
|
|
273
|
+
const currentPrefix = getPrefix(currentValue);
|
|
274
|
+
if (currentPrefix === newPrefix && (currentValue === newValue || hash(currentValue) === hash(newValue))) {
|
|
275
|
+
const newMultiplicity = currentMultiplicity + multiplicity;
|
|
276
|
+
if (newMultiplicity === 0) {
|
|
277
|
+
__privateGet(this, _inner).delete(key);
|
|
278
|
+
} else {
|
|
279
|
+
__privateGet(this, _inner).set(key, [newValue, newMultiplicity]);
|
|
280
|
+
}
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (currentPrefix === NO_PREFIX && newPrefix === NO_PREFIX) {
|
|
284
|
+
const valueMap = new ValueMap();
|
|
285
|
+
valueMap.set(hash(currentValue), currentSingleValue);
|
|
286
|
+
valueMap.set(hash(newValue), [newValue, multiplicity]);
|
|
287
|
+
__privateGet(this, _inner).set(key, valueMap);
|
|
288
|
+
} else {
|
|
289
|
+
const prefixMap = new PrefixMap();
|
|
290
|
+
if (currentPrefix === newPrefix) {
|
|
291
|
+
const valueMap = new ValueMap();
|
|
292
|
+
valueMap.set(hash(currentValue), currentSingleValue);
|
|
293
|
+
valueMap.set(hash(newValue), [newValue, multiplicity]);
|
|
294
|
+
prefixMap.set(currentPrefix, valueMap);
|
|
295
|
+
} else {
|
|
296
|
+
prefixMap.set(currentPrefix, currentSingleValue);
|
|
297
|
+
prefixMap.set(newPrefix, [newValue, multiplicity]);
|
|
298
|
+
}
|
|
299
|
+
__privateGet(this, _inner).set(key, prefixMap);
|
|
151
300
|
}
|
|
152
301
|
};
|
|
302
|
+
function getPrefix(value) {
|
|
303
|
+
if (Array.isArray(value) && (typeof value[0] === `string` || typeof value[0] === `number` || typeof value[0] === `bigint`)) {
|
|
304
|
+
return value[0];
|
|
305
|
+
}
|
|
306
|
+
return NO_PREFIX;
|
|
307
|
+
}
|
|
308
|
+
function isSingleValue(value) {
|
|
309
|
+
return Array.isArray(value);
|
|
310
|
+
}
|
|
153
311
|
export {
|
|
154
312
|
Index
|
|
155
313
|
};
|