@tanstack/db-ivm 0.1.13 → 0.1.14
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/README.md +3 -3
- package/dist/cjs/d2.cjs.map +1 -1
- package/dist/cjs/graph.cjs.map +1 -1
- package/dist/cjs/hashing/hash.cjs.map +1 -1
- package/dist/cjs/index.cjs +2 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +1 -0
- package/dist/cjs/indexes.cjs.map +1 -1
- package/dist/cjs/multiset.cjs.map +1 -1
- package/dist/cjs/operators/concat.cjs.map +1 -1
- package/dist/cjs/operators/consolidate.cjs.map +1 -1
- package/dist/cjs/operators/count.cjs.map +1 -1
- package/dist/cjs/operators/debug.cjs.map +1 -1
- package/dist/cjs/operators/distinct.cjs.map +1 -1
- package/dist/cjs/operators/filter.cjs.map +1 -1
- package/dist/cjs/operators/filterBy.cjs.map +1 -1
- package/dist/cjs/operators/groupBy.cjs.map +1 -1
- package/dist/cjs/operators/join.cjs.map +1 -1
- package/dist/cjs/operators/keying.cjs.map +1 -1
- package/dist/cjs/operators/map.cjs.map +1 -1
- package/dist/cjs/operators/negate.cjs.map +1 -1
- package/dist/cjs/operators/orderBy.cjs.map +1 -1
- package/dist/cjs/operators/output.cjs.map +1 -1
- package/dist/cjs/operators/pipe.cjs.map +1 -1
- package/dist/cjs/operators/reduce.cjs.map +1 -1
- package/dist/cjs/operators/tap.cjs.map +1 -1
- package/dist/cjs/operators/topK.cjs.map +1 -1
- package/dist/cjs/operators/topKWithFractionalIndex.cjs +20 -35
- package/dist/cjs/operators/topKWithFractionalIndex.cjs.map +1 -1
- package/dist/cjs/operators/topKWithFractionalIndex.d.cts +3 -11
- package/dist/cjs/operators/topKWithFractionalIndexBTree.d.cts +4 -4
- package/dist/cjs/utils.cjs +9 -0
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +5 -0
- package/dist/esm/d2.js.map +1 -1
- package/dist/esm/graph.js.map +1 -1
- package/dist/esm/hashing/hash.js.map +1 -1
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/indexes.js.map +1 -1
- package/dist/esm/multiset.js.map +1 -1
- package/dist/esm/operators/concat.js.map +1 -1
- package/dist/esm/operators/consolidate.js.map +1 -1
- package/dist/esm/operators/count.js.map +1 -1
- package/dist/esm/operators/debug.js.map +1 -1
- package/dist/esm/operators/distinct.js.map +1 -1
- package/dist/esm/operators/filter.js.map +1 -1
- package/dist/esm/operators/filterBy.js.map +1 -1
- package/dist/esm/operators/groupBy.js.map +1 -1
- package/dist/esm/operators/join.js.map +1 -1
- package/dist/esm/operators/keying.js.map +1 -1
- package/dist/esm/operators/map.js.map +1 -1
- package/dist/esm/operators/negate.js.map +1 -1
- package/dist/esm/operators/orderBy.js.map +1 -1
- package/dist/esm/operators/output.js.map +1 -1
- package/dist/esm/operators/pipe.js.map +1 -1
- package/dist/esm/operators/reduce.js.map +1 -1
- package/dist/esm/operators/tap.js.map +1 -1
- package/dist/esm/operators/topK.js.map +1 -1
- package/dist/esm/operators/topKWithFractionalIndex.d.ts +3 -11
- package/dist/esm/operators/topKWithFractionalIndex.js +21 -36
- package/dist/esm/operators/topKWithFractionalIndex.js.map +1 -1
- package/dist/esm/operators/topKWithFractionalIndexBTree.d.ts +4 -4
- package/dist/esm/utils.d.ts +5 -0
- package/dist/esm/utils.js +9 -0
- package/dist/esm/utils.js.map +1 -1
- package/package.json +29 -29
- package/src/d2.ts +4 -4
- package/src/graph.ts +6 -6
- package/src/hashing/hash.ts +3 -3
- package/src/hashing/index.ts +2 -2
- package/src/index.ts +5 -4
- package/src/indexes.ts +8 -8
- package/src/multiset.ts +5 -5
- package/src/operators/concat.ts +6 -6
- package/src/operators/consolidate.ts +6 -6
- package/src/operators/count.ts +9 -9
- package/src/operators/debug.ts +8 -8
- package/src/operators/distinct.ts +11 -11
- package/src/operators/filter.ts +8 -8
- package/src/operators/filterBy.ts +7 -7
- package/src/operators/groupBy.ts +22 -22
- package/src/operators/index.ts +19 -19
- package/src/operators/join.ts +23 -23
- package/src/operators/keying.ts +4 -4
- package/src/operators/map.ts +8 -8
- package/src/operators/negate.ts +6 -6
- package/src/operators/orderBy.ts +26 -26
- package/src/operators/orderByBTree.ts +7 -7
- package/src/operators/output.ts +9 -9
- package/src/operators/pipe.ts +1 -1
- package/src/operators/reduce.ts +9 -9
- package/src/operators/tap.ts +8 -8
- package/src/operators/topK.ts +8 -8
- package/src/operators/topKWithFractionalIndex.ts +62 -83
- package/src/operators/topKWithFractionalIndexBTree.ts +19 -20
- package/src/types.ts +22 -22
- package/src/utils.ts +19 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"join.cjs","sources":["../../../src/operators/join.ts"],"sourcesContent":["/**\n * # Direct Join Algorithms for Incremental View Maintenance\n *\n * High-performance join operations implementing all join types (inner, left, right, full, anti)\n * with minimal state and optimized performance.\n *\n * ## Algorithm\n *\n * For each tick, the algorithm processes incoming changes (deltas) and emits join results:\n *\n * 1. **Build deltas**: Create delta indexes from input messages using `Index.fromMultiSet()`\n * 2. **Inner results**: Emit `ΔA⋈B_old + A_old⋈ΔB + ΔA⋈ΔB` (matched pairs)\n * 3. **Outer results**: For unmatched rows, emit null-extended tuples:\n * - New unmatched rows from deltas (when opposite side empty)\n * - Presence transitions: when key goes `0→>0` (retract nulls) or `>0→0` (emit nulls)\n * 4. **Update state**: Append deltas to indexes (consolidated multiplicity tracking automatic)\n *\n * **Consolidated multiplicity tracking** enables O(1) presence checks instead of scanning index buckets.\n *\n * ## State\n *\n * **Indexes** store the actual data:\n * - `indexA: Index<K, V1>` - all left-side rows accumulated over time\n * - `indexB: Index<K, V2>` - all right-side rows accumulated over time\n *\n * **Consolidated multiplicity tracking** (built into Index):\n * - Each Index maintains sum of multiplicities per key internally\n * - Provides O(1) presence checks: `index.hasPresence(key)` and `index.getConsolidatedMultiplicity(key)`\n * - Avoids scanning entire index buckets just to check if key has any rows\n *\n * ## Join Types\n *\n * - **Inner**: Standard delta terms only\n * - **Outer**: Inner results + null-extended unmatched rows with transition handling\n * - **Anti**: Unmatched rows only (no inner results)\n *\n * ## Key Optimizations\n *\n * - **No temp copying**: Uses `(A⊎ΔA)⋈ΔB = A⋈ΔB ⊎ ΔA⋈ΔB` distributive property\n * - **Early-out checks**: Skip phases when no deltas present\n * - **Zero-entry pruning**: Keep maps compact, O(distinct keys) memory\n * - **Final presence logic**: Avoid emit→retract churn within same tick\n *\n * ## Correctness\n *\n * - **Ordering**: Pre-append snapshots for emissions, post-emit state updates\n * - **Presence**: Key matched iff mass ≠ 0, transitions trigger null handling\n * - **Bag semantics**: Proper multiplicity handling including negatives\n */\n\nimport { BinaryOperator, DifferenceStreamWriter } from \"../graph.js\"\nimport { StreamBuilder } from \"../d2.js\"\nimport { MultiSet } from \"../multiset.js\"\nimport { Index } from \"../indexes.js\"\nimport type { DifferenceStreamReader } from \"../graph.js\"\nimport type { IStreamBuilder, KeyValue, PipedOperator } from \"../types.js\"\n\n/**\n * Type of join to perform\n */\nexport type JoinType = `inner` | `left` | `right` | `full` | `anti`\n\n/**\n * Operator that joins two input streams using direct join algorithms\n */\nexport class JoinOperator<K, V1, V2> extends BinaryOperator<\n [K, V1] | [K, V2] | [K, [V1, V2]] | [K, [V1 | null, V2 | null]]\n> {\n #indexA = new Index<K, V1>()\n #indexB = new Index<K, V2>()\n #mode: JoinType\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, V1]>,\n inputB: DifferenceStreamReader<[K, V2]>,\n output: DifferenceStreamWriter<any>,\n mode: JoinType = `inner`\n ) {\n super(id, inputA, inputB, output)\n this.#mode = mode\n }\n\n run(): void {\n // Build deltas from input messages\n const deltaA = Index.fromMultiSets<K, V1>(\n this.inputAMessages() as Array<MultiSet<[K, V1]>>\n )\n const deltaB = Index.fromMultiSets<K, V2>(\n this.inputBMessages() as Array<MultiSet<[K, V2]>>\n )\n\n // Early-out if nothing changed\n if (deltaA.size === 0 && deltaB.size === 0) return\n\n const results = new MultiSet<any>()\n\n // Emit inner results (all modes except anti)\n if (this.#mode !== `anti`) {\n this.emitInnerResults(deltaA, deltaB, results)\n }\n\n // Emit left outer/anti results\n if (\n this.#mode === `left` ||\n this.#mode === `full` ||\n this.#mode === `anti`\n ) {\n this.emitLeftOuterResults(deltaA, deltaB, results)\n }\n\n // Emit right outer results\n if (this.#mode === `right` || this.#mode === `full`) {\n this.emitRightOuterResults(deltaA, deltaB, results)\n }\n\n // Update state and send results\n // IMPORTANT: All emissions use pre-append snapshots of indexA/indexB.\n // Now append ALL deltas to indices - this happens unconditionally for every key,\n // regardless of whether presence flipped. Consolidated multiplicity tracking is automatic.\n this.#indexA.append(deltaA)\n this.#indexB.append(deltaB)\n\n // Send results\n if (results.getInner().length > 0) {\n this.output.sendData(results)\n }\n }\n\n private emitInnerResults(\n deltaA: Index<K, V1>,\n deltaB: Index<K, V2>,\n results: MultiSet<any>\n ): void {\n // Emit the three standard delta terms: ΔA⋈B_old, A_old⋈ΔB, ΔA⋈ΔB\n if (deltaA.size > 0) results.extend(deltaA.join(this.#indexB))\n if (deltaB.size > 0) results.extend(this.#indexA.join(deltaB))\n if (deltaA.size > 0 && deltaB.size > 0) results.extend(deltaA.join(deltaB))\n }\n\n private emitLeftOuterResults(\n deltaA: Index<K, V1>,\n deltaB: Index<K, V2>,\n results: MultiSet<any>\n ): void {\n // Emit unmatched left rows from deltaA\n if (deltaA.size > 0) {\n for (const [key, valueIterator] of deltaA.entriesIterators()) {\n const currentMultiplicityB =\n this.#indexB.getConsolidatedMultiplicity(key)\n const deltaMultiplicityB = deltaB.getConsolidatedMultiplicity(key)\n const finalMultiplicityB = currentMultiplicityB + deltaMultiplicityB\n\n if (finalMultiplicityB === 0) {\n for (const [value, multiplicity] of valueIterator) {\n if (multiplicity !== 0) {\n results.add([key, [value, null]], multiplicity)\n }\n }\n }\n }\n }\n\n // Handle presence transitions from right side changes\n if (deltaB.size > 0) {\n for (const key of deltaB.getPresenceKeys()) {\n const before = this.#indexB.getConsolidatedMultiplicity(key)\n const deltaMult = deltaB.getConsolidatedMultiplicity(key)\n if (deltaMult === 0) continue\n const after = before + deltaMult\n\n // Skip transition handling if presence doesn't flip (both zero or both non-zero)\n // Note: Index updates happen later regardless - we're only skipping null-extension emissions here\n if ((before === 0) === (after === 0)) continue\n\n // Determine the type of transition:\n // - 0 → non-zero: Right becomes non-empty, left rows transition from unmatched to matched\n // → RETRACT previously emitted null-extended rows (emit with negative multiplicity)\n // - non-zero → 0: Right becomes empty, left rows transition from matched to unmatched\n // → EMIT new null-extended rows (emit with positive multiplicity)\n const transitioningToMatched = before === 0\n\n for (const [value, multiplicity] of this.#indexA.getIterator(key)) {\n if (multiplicity !== 0) {\n results.add(\n [key, [value, null]],\n transitioningToMatched ? -multiplicity : +multiplicity\n )\n }\n }\n }\n }\n }\n\n private emitRightOuterResults(\n deltaA: Index<K, V1>,\n deltaB: Index<K, V2>,\n results: MultiSet<any>\n ): void {\n // Emit unmatched right rows from deltaB\n if (deltaB.size > 0) {\n for (const [key, valueIterator] of deltaB.entriesIterators()) {\n const currentMultiplicityA =\n this.#indexA.getConsolidatedMultiplicity(key)\n const deltaMultiplicityA = deltaA.getConsolidatedMultiplicity(key)\n const finalMultiplicityA = currentMultiplicityA + deltaMultiplicityA\n\n if (finalMultiplicityA === 0) {\n for (const [value, multiplicity] of valueIterator) {\n if (multiplicity !== 0) {\n results.add([key, [null, value]], multiplicity)\n }\n }\n }\n }\n }\n\n // Handle presence transitions from left side changes\n if (deltaA.size > 0) {\n for (const key of deltaA.getPresenceKeys()) {\n const before = this.#indexA.getConsolidatedMultiplicity(key)\n const deltaMult = deltaA.getConsolidatedMultiplicity(key)\n if (deltaMult === 0) continue\n const after = before + deltaMult\n\n // Skip transition handling if presence doesn't flip (both zero or both non-zero)\n // Note: Index updates happen later regardless - we're only skipping null-extension emissions here\n if ((before === 0) === (after === 0)) continue\n\n // Determine the type of transition:\n // - 0 → non-zero: Left becomes non-empty, right rows transition from unmatched to matched\n // → RETRACT previously emitted null-extended rows (emit with negative multiplicity)\n // - non-zero → 0: Left becomes empty, right rows transition from matched to unmatched\n // → EMIT new null-extended rows (emit with positive multiplicity)\n const transitioningToMatched = before === 0\n\n for (const [value, multiplicity] of this.#indexB.getIterator(key)) {\n if (multiplicity !== 0) {\n results.add(\n [key, [null, value]],\n transitioningToMatched ? -multiplicity : +multiplicity\n )\n }\n }\n }\n }\n }\n}\n\n/**\n * Joins two input streams\n * @param other - The other stream to join with\n * @param type - The type of join to perform\n */\nexport function join<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>,\n type: JoinType = `inner`\n): PipedOperator<T, KeyValue<K, [V1 | null, V2 | null]>> {\n return (\n stream: IStreamBuilder<T>\n ): IStreamBuilder<KeyValue<K, [V1 | null, V2 | null]>> => {\n if (stream.graph !== other.graph) {\n throw new Error(`Cannot join streams from different graphs`)\n }\n const output = new StreamBuilder<KeyValue<K, [V1 | null, V2 | null]>>(\n stream.graph,\n new DifferenceStreamWriter<KeyValue<K, [V1 | null, V2 | null]>>()\n )\n const operator = new JoinOperator<K, V1, V2>(\n stream.graph.getNextOperatorId(),\n stream.connectReader() as DifferenceStreamReader<KeyValue<K, V1>>,\n other.connectReader(),\n output.writer,\n type\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n\n/**\n * Joins two input streams (inner join)\n * @param other - The other stream to join with\n */\nexport function innerJoin<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>\n): PipedOperator<T, KeyValue<K, [V1, V2]>> {\n return join(other, `inner`) as unknown as PipedOperator<\n T,\n KeyValue<K, [V1, V2]>\n >\n}\n\n/**\n * Joins two input streams (anti join)\n * @param other - The other stream to join with\n */\nexport function antiJoin<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>\n): PipedOperator<T, KeyValue<K, [V1, null]>> {\n return join(other, `anti`) as unknown as PipedOperator<\n T,\n KeyValue<K, [V1, null]>\n >\n}\n\n/**\n * Joins two input streams (left join)\n * @param other - The other stream to join with\n */\nexport function leftJoin<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>\n): PipedOperator<T, KeyValue<K, [V1, V2 | null]>> {\n return join(other, `left`) as unknown as PipedOperator<\n T,\n KeyValue<K, [V1, V2 | null]>\n >\n}\n\n/**\n * Joins two input streams (right join)\n * @param other - The other stream to join with\n */\nexport function rightJoin<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>\n): PipedOperator<T, KeyValue<K, [V1 | null, V2]>> {\n return join(other, `right`) as unknown as PipedOperator<\n T,\n KeyValue<K, [V1 | null, V2]>\n >\n}\n\n/**\n * Joins two input streams (full join)\n * @param other - The other stream to join with\n */\nexport function fullJoin<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>\n): PipedOperator<T, KeyValue<K, [V1 | null, V2 | null]>> {\n return join(other, `full`) as unknown as PipedOperator<\n T,\n KeyValue<K, [V1 | null, V2 | null]>\n >\n}\n"],"names":["BinaryOperator","Index","MultiSet","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;;;AAiEO,MAAM,qBAAgCA,MAAAA,eAE3C;AAAA,EACA,UAAU,IAAIC,QAAAA,MAAA;AAAA,EACd,UAAU,IAAIA,QAAAA,MAAA;AAAA,EACd;AAAA,EAEA,YACE,IACA,QACA,QACA,QACA,OAAiB,SACjB;AACA,UAAM,IAAI,QAAQ,QAAQ,MAAM;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AACvD,SAAO,KAAK,OAAO,MAAM;AAI3B;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"join.cjs","sources":["../../../src/operators/join.ts"],"sourcesContent":["/**\n * # Direct Join Algorithms for Incremental View Maintenance\n *\n * High-performance join operations implementing all join types (inner, left, right, full, anti)\n * with minimal state and optimized performance.\n *\n * ## Algorithm\n *\n * For each tick, the algorithm processes incoming changes (deltas) and emits join results:\n *\n * 1. **Build deltas**: Create delta indexes from input messages using `Index.fromMultiSet()`\n * 2. **Inner results**: Emit `ΔA⋈B_old + A_old⋈ΔB + ΔA⋈ΔB` (matched pairs)\n * 3. **Outer results**: For unmatched rows, emit null-extended tuples:\n * - New unmatched rows from deltas (when opposite side empty)\n * - Presence transitions: when key goes `0→>0` (retract nulls) or `>0→0` (emit nulls)\n * 4. **Update state**: Append deltas to indexes (consolidated multiplicity tracking automatic)\n *\n * **Consolidated multiplicity tracking** enables O(1) presence checks instead of scanning index buckets.\n *\n * ## State\n *\n * **Indexes** store the actual data:\n * - `indexA: Index<K, V1>` - all left-side rows accumulated over time\n * - `indexB: Index<K, V2>` - all right-side rows accumulated over time\n *\n * **Consolidated multiplicity tracking** (built into Index):\n * - Each Index maintains sum of multiplicities per key internally\n * - Provides O(1) presence checks: `index.hasPresence(key)` and `index.getConsolidatedMultiplicity(key)`\n * - Avoids scanning entire index buckets just to check if key has any rows\n *\n * ## Join Types\n *\n * - **Inner**: Standard delta terms only\n * - **Outer**: Inner results + null-extended unmatched rows with transition handling\n * - **Anti**: Unmatched rows only (no inner results)\n *\n * ## Key Optimizations\n *\n * - **No temp copying**: Uses `(A⊎ΔA)⋈ΔB = A⋈ΔB ⊎ ΔA⋈ΔB` distributive property\n * - **Early-out checks**: Skip phases when no deltas present\n * - **Zero-entry pruning**: Keep maps compact, O(distinct keys) memory\n * - **Final presence logic**: Avoid emit→retract churn within same tick\n *\n * ## Correctness\n *\n * - **Ordering**: Pre-append snapshots for emissions, post-emit state updates\n * - **Presence**: Key matched iff mass ≠ 0, transitions trigger null handling\n * - **Bag semantics**: Proper multiplicity handling including negatives\n */\n\nimport { BinaryOperator, DifferenceStreamWriter } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport { MultiSet } from '../multiset.js'\nimport { Index } from '../indexes.js'\nimport type { DifferenceStreamReader } from '../graph.js'\nimport type { IStreamBuilder, KeyValue, PipedOperator } from '../types.js'\n\n/**\n * Type of join to perform\n */\nexport type JoinType = `inner` | `left` | `right` | `full` | `anti`\n\n/**\n * Operator that joins two input streams using direct join algorithms\n */\nexport class JoinOperator<K, V1, V2> extends BinaryOperator<\n [K, V1] | [K, V2] | [K, [V1, V2]] | [K, [V1 | null, V2 | null]]\n> {\n #indexA = new Index<K, V1>()\n #indexB = new Index<K, V2>()\n #mode: JoinType\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, V1]>,\n inputB: DifferenceStreamReader<[K, V2]>,\n output: DifferenceStreamWriter<any>,\n mode: JoinType = `inner`,\n ) {\n super(id, inputA, inputB, output)\n this.#mode = mode\n }\n\n run(): void {\n // Build deltas from input messages\n const deltaA = Index.fromMultiSets<K, V1>(\n this.inputAMessages() as Array<MultiSet<[K, V1]>>,\n )\n const deltaB = Index.fromMultiSets<K, V2>(\n this.inputBMessages() as Array<MultiSet<[K, V2]>>,\n )\n\n // Early-out if nothing changed\n if (deltaA.size === 0 && deltaB.size === 0) return\n\n const results = new MultiSet<any>()\n\n // Emit inner results (all modes except anti)\n if (this.#mode !== `anti`) {\n this.emitInnerResults(deltaA, deltaB, results)\n }\n\n // Emit left outer/anti results\n if (\n this.#mode === `left` ||\n this.#mode === `full` ||\n this.#mode === `anti`\n ) {\n this.emitLeftOuterResults(deltaA, deltaB, results)\n }\n\n // Emit right outer results\n if (this.#mode === `right` || this.#mode === `full`) {\n this.emitRightOuterResults(deltaA, deltaB, results)\n }\n\n // Update state and send results\n // IMPORTANT: All emissions use pre-append snapshots of indexA/indexB.\n // Now append ALL deltas to indices - this happens unconditionally for every key,\n // regardless of whether presence flipped. Consolidated multiplicity tracking is automatic.\n this.#indexA.append(deltaA)\n this.#indexB.append(deltaB)\n\n // Send results\n if (results.getInner().length > 0) {\n this.output.sendData(results)\n }\n }\n\n private emitInnerResults(\n deltaA: Index<K, V1>,\n deltaB: Index<K, V2>,\n results: MultiSet<any>,\n ): void {\n // Emit the three standard delta terms: ΔA⋈B_old, A_old⋈ΔB, ΔA⋈ΔB\n if (deltaA.size > 0) results.extend(deltaA.join(this.#indexB))\n if (deltaB.size > 0) results.extend(this.#indexA.join(deltaB))\n if (deltaA.size > 0 && deltaB.size > 0) results.extend(deltaA.join(deltaB))\n }\n\n private emitLeftOuterResults(\n deltaA: Index<K, V1>,\n deltaB: Index<K, V2>,\n results: MultiSet<any>,\n ): void {\n // Emit unmatched left rows from deltaA\n if (deltaA.size > 0) {\n for (const [key, valueIterator] of deltaA.entriesIterators()) {\n const currentMultiplicityB =\n this.#indexB.getConsolidatedMultiplicity(key)\n const deltaMultiplicityB = deltaB.getConsolidatedMultiplicity(key)\n const finalMultiplicityB = currentMultiplicityB + deltaMultiplicityB\n\n if (finalMultiplicityB === 0) {\n for (const [value, multiplicity] of valueIterator) {\n if (multiplicity !== 0) {\n results.add([key, [value, null]], multiplicity)\n }\n }\n }\n }\n }\n\n // Handle presence transitions from right side changes\n if (deltaB.size > 0) {\n for (const key of deltaB.getPresenceKeys()) {\n const before = this.#indexB.getConsolidatedMultiplicity(key)\n const deltaMult = deltaB.getConsolidatedMultiplicity(key)\n if (deltaMult === 0) continue\n const after = before + deltaMult\n\n // Skip transition handling if presence doesn't flip (both zero or both non-zero)\n // Note: Index updates happen later regardless - we're only skipping null-extension emissions here\n if ((before === 0) === (after === 0)) continue\n\n // Determine the type of transition:\n // - 0 → non-zero: Right becomes non-empty, left rows transition from unmatched to matched\n // → RETRACT previously emitted null-extended rows (emit with negative multiplicity)\n // - non-zero → 0: Right becomes empty, left rows transition from matched to unmatched\n // → EMIT new null-extended rows (emit with positive multiplicity)\n const transitioningToMatched = before === 0\n\n for (const [value, multiplicity] of this.#indexA.getIterator(key)) {\n if (multiplicity !== 0) {\n results.add(\n [key, [value, null]],\n transitioningToMatched ? -multiplicity : +multiplicity,\n )\n }\n }\n }\n }\n }\n\n private emitRightOuterResults(\n deltaA: Index<K, V1>,\n deltaB: Index<K, V2>,\n results: MultiSet<any>,\n ): void {\n // Emit unmatched right rows from deltaB\n if (deltaB.size > 0) {\n for (const [key, valueIterator] of deltaB.entriesIterators()) {\n const currentMultiplicityA =\n this.#indexA.getConsolidatedMultiplicity(key)\n const deltaMultiplicityA = deltaA.getConsolidatedMultiplicity(key)\n const finalMultiplicityA = currentMultiplicityA + deltaMultiplicityA\n\n if (finalMultiplicityA === 0) {\n for (const [value, multiplicity] of valueIterator) {\n if (multiplicity !== 0) {\n results.add([key, [null, value]], multiplicity)\n }\n }\n }\n }\n }\n\n // Handle presence transitions from left side changes\n if (deltaA.size > 0) {\n for (const key of deltaA.getPresenceKeys()) {\n const before = this.#indexA.getConsolidatedMultiplicity(key)\n const deltaMult = deltaA.getConsolidatedMultiplicity(key)\n if (deltaMult === 0) continue\n const after = before + deltaMult\n\n // Skip transition handling if presence doesn't flip (both zero or both non-zero)\n // Note: Index updates happen later regardless - we're only skipping null-extension emissions here\n if ((before === 0) === (after === 0)) continue\n\n // Determine the type of transition:\n // - 0 → non-zero: Left becomes non-empty, right rows transition from unmatched to matched\n // → RETRACT previously emitted null-extended rows (emit with negative multiplicity)\n // - non-zero → 0: Left becomes empty, right rows transition from matched to unmatched\n // → EMIT new null-extended rows (emit with positive multiplicity)\n const transitioningToMatched = before === 0\n\n for (const [value, multiplicity] of this.#indexB.getIterator(key)) {\n if (multiplicity !== 0) {\n results.add(\n [key, [null, value]],\n transitioningToMatched ? -multiplicity : +multiplicity,\n )\n }\n }\n }\n }\n }\n}\n\n/**\n * Joins two input streams\n * @param other - The other stream to join with\n * @param type - The type of join to perform\n */\nexport function join<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>,\n type: JoinType = `inner`,\n): PipedOperator<T, KeyValue<K, [V1 | null, V2 | null]>> {\n return (\n stream: IStreamBuilder<T>,\n ): IStreamBuilder<KeyValue<K, [V1 | null, V2 | null]>> => {\n if (stream.graph !== other.graph) {\n throw new Error(`Cannot join streams from different graphs`)\n }\n const output = new StreamBuilder<KeyValue<K, [V1 | null, V2 | null]>>(\n stream.graph,\n new DifferenceStreamWriter<KeyValue<K, [V1 | null, V2 | null]>>(),\n )\n const operator = new JoinOperator<K, V1, V2>(\n stream.graph.getNextOperatorId(),\n stream.connectReader() as DifferenceStreamReader<KeyValue<K, V1>>,\n other.connectReader(),\n output.writer,\n type,\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n\n/**\n * Joins two input streams (inner join)\n * @param other - The other stream to join with\n */\nexport function innerJoin<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>,\n): PipedOperator<T, KeyValue<K, [V1, V2]>> {\n return join(other, `inner`) as unknown as PipedOperator<\n T,\n KeyValue<K, [V1, V2]>\n >\n}\n\n/**\n * Joins two input streams (anti join)\n * @param other - The other stream to join with\n */\nexport function antiJoin<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>,\n): PipedOperator<T, KeyValue<K, [V1, null]>> {\n return join(other, `anti`) as unknown as PipedOperator<\n T,\n KeyValue<K, [V1, null]>\n >\n}\n\n/**\n * Joins two input streams (left join)\n * @param other - The other stream to join with\n */\nexport function leftJoin<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>,\n): PipedOperator<T, KeyValue<K, [V1, V2 | null]>> {\n return join(other, `left`) as unknown as PipedOperator<\n T,\n KeyValue<K, [V1, V2 | null]>\n >\n}\n\n/**\n * Joins two input streams (right join)\n * @param other - The other stream to join with\n */\nexport function rightJoin<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>,\n): PipedOperator<T, KeyValue<K, [V1 | null, V2]>> {\n return join(other, `right`) as unknown as PipedOperator<\n T,\n KeyValue<K, [V1 | null, V2]>\n >\n}\n\n/**\n * Joins two input streams (full join)\n * @param other - The other stream to join with\n */\nexport function fullJoin<\n K,\n V1 extends T extends KeyValue<infer _KT, infer VT> ? VT : never,\n V2,\n T,\n>(\n other: IStreamBuilder<KeyValue<K, V2>>,\n): PipedOperator<T, KeyValue<K, [V1 | null, V2 | null]>> {\n return join(other, `full`) as unknown as PipedOperator<\n T,\n KeyValue<K, [V1 | null, V2 | null]>\n >\n}\n"],"names":["BinaryOperator","Index","MultiSet","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;;;AAiEO,MAAM,qBAAgCA,MAAAA,eAE3C;AAAA,EACA,UAAU,IAAIC,QAAAA,MAAA;AAAA,EACd,UAAU,IAAIA,QAAAA,MAAA;AAAA,EACd;AAAA,EAEA,YACE,IACA,QACA,QACA,QACA,OAAiB,SACjB;AACA,UAAM,IAAI,QAAQ,QAAQ,MAAM;AAChC,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,MAAY;AAEV,UAAM,SAASA,QAAAA,MAAM;AAAA,MACnB,KAAK,eAAA;AAAA,IAAe;AAEtB,UAAM,SAASA,QAAAA,MAAM;AAAA,MACnB,KAAK,eAAA;AAAA,IAAe;AAItB,QAAI,OAAO,SAAS,KAAK,OAAO,SAAS,EAAG;AAE5C,UAAM,UAAU,IAAIC,kBAAA;AAGpB,QAAI,KAAK,UAAU,QAAQ;AACzB,WAAK,iBAAiB,QAAQ,QAAQ,OAAO;AAAA,IAC/C;AAGA,QACE,KAAK,UAAU,UACf,KAAK,UAAU,UACf,KAAK,UAAU,QACf;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AA,cACnB,yBAAyB,CAAC,eAAe,CAAC;AAAA,YAAA;AAAA,UAE9C;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAOO,SAAS,KAMd,OACA,OAAiB,SACsC;AACvD,SAAO,CACL,WACwD;AACxD,QAAI,OAAO,UAAU,MAAM,OAAO;AAChC,YAAM,IAAI,MAAM,2CAA2C;AAAA,IAC7D;AACA,UAAM,SAAS,IAAIC,GAAAA;AAAAA,MACjB,OAAO;AAAA,MACP,IAAIC,MAAAA,uBAAA;AAAA,IAA4D;AAElE,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,MAAM,cAAA;AAAA,MACN,OAAO;AAAA,MACP;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;AAMO,SAAS,UAMd,OACyC;AACzC,SAAO,KAAK,OAAO,OAAO;AAI5B;AAMO,SAAS,SAMd,OAC2C;AAC3C,SAAO,KAAK,OAAO,MAAM;AAI3B;AAMO,SAAS,SAMd,OACgD;AAChD,SAAO,KAAK,OAAO,MAAM;AAI3B;AAMO,SAAS,UAMd,OACgD;AAChD,SAAO,KAAK,OAAO,OAAO;AAI5B;AAMO,SAAS,SAMd,OACuD;AACvD,SAAO,KAAK,OAAO,MAAM;AAI3B;;;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keying.cjs","sources":["../../../src/operators/keying.ts"],"sourcesContent":["import { map } from
|
|
1
|
+
{"version":3,"file":"keying.cjs","sources":["../../../src/operators/keying.ts"],"sourcesContent":["import { map } from './map.js'\nimport type { PipedOperator } from '../types.js'\n\n/**\n * Type for a keyed value\n */\nexport type Keyed<K, V> = [K, V]\n\n/**\n * Takes an unkeyed input and returns a keyed result\n * @param keyFn - Function to generate the key for each value\n */\nexport function keyBy<T, K>(\n keyFn: (value: T) => K,\n): PipedOperator<T, Keyed<K, T>> {\n return map((value: T): Keyed<K, T> => [keyFn(value), value])\n}\n\n/**\n * Removes the key from a keyed stream\n */\nexport function unkey<K, V>(): PipedOperator<Keyed<K, V>, V> {\n return map(([_, value]: Keyed<K, V>): V => value)\n}\n\n/**\n * Takes a keyed input and rekeys it with a new key\n * @param keyFn - Function to generate the new key for each value\n */\nexport function rekey<K1, K2, V>(\n keyFn: (value: V) => K2,\n): PipedOperator<Keyed<K1, V>, Keyed<K2, V>> {\n return map(([_, value]: Keyed<K1, V>): Keyed<K2, V> => [keyFn(value), value])\n}\n"],"names":["map"],"mappings":";;;AAYO,SAAS,MACd,OAC+B;AAC/B,SAAOA,IAAAA,IAAI,CAAC,UAA0B,CAAC,MAAM,KAAK,GAAG,KAAK,CAAC;AAC7D;AAKO,SAAS,QAA6C;AAC3D,SAAOA,IAAAA,IAAI,CAAC,CAAC,GAAG,KAAK,MAAsB,KAAK;AAClD;AAMO,SAAS,MACd,OAC2C;AAC3C,SAAOA,IAAAA,IAAI,CAAC,CAAC,GAAG,KAAK,MAAkC,CAAC,MAAM,KAAK,GAAG,KAAK,CAAC;AAC9E;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"map.cjs","sources":["../../../src/operators/map.ts"],"sourcesContent":["import { DifferenceStreamWriter, LinearUnaryOperator } from
|
|
1
|
+
{"version":3,"file":"map.cjs","sources":["../../../src/operators/map.ts"],"sourcesContent":["import { DifferenceStreamWriter, LinearUnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport type { IStreamBuilder, PipedOperator } from '../types.js'\nimport type { DifferenceStreamReader } from '../graph.js'\nimport type { MultiSet } from '../multiset.js'\n\n/**\n * Operator that applies a function to each element in the input stream\n */\nexport class MapOperator<T, U> extends LinearUnaryOperator<T, U> {\n #f: (data: T) => U\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<T>,\n output: DifferenceStreamWriter<U>,\n f: (data: T) => U,\n ) {\n super(id, inputA, output)\n this.#f = f\n }\n\n inner(collection: MultiSet<T>): MultiSet<U> {\n return collection.map(this.#f)\n }\n}\n\n/**\n * Applies a function to each element in the input stream\n * @param f - The function to apply to each element\n */\nexport function map<T, O>(f: (data: T) => O): PipedOperator<T, O> {\n return (stream: IStreamBuilder<T>): IStreamBuilder<O> => {\n const output = new StreamBuilder<O>(\n stream.graph,\n new DifferenceStreamWriter<O>(),\n )\n const operator = new MapOperator<T, O>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n f,\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":["LinearUnaryOperator","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;AASO,MAAM,oBAA0BA,MAAAA,oBAA0B;AAAA,EAC/D;AAAA,EAEA,YACE,IACA,QACA,QACA,GACA;AACA,UAAM,IAAI,QAAQ,MAAM;AACxB,SAAK,KAAK;AAAA,EACZ;AAAA,EAEA,MAAM,YAAsC;AAC1C,WAAO,WAAW,IAAI,KAAK,EAAE;AAAA,EAC/B;AACF;AAMO,SAAS,IAAU,GAAwC;AAChE,SAAO,CAAC,WAAiD;AACvD,UAAM,SAAS,IAAIC,GAAAA;AAAAA,MACjB,OAAO;AAAA,MACP,IAAIC,MAAAA,uBAAA;AAAA,IAA0B;AAEhC,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"negate.cjs","sources":["../../../src/operators/negate.ts"],"sourcesContent":["import { DifferenceStreamWriter, LinearUnaryOperator } from
|
|
1
|
+
{"version":3,"file":"negate.cjs","sources":["../../../src/operators/negate.ts"],"sourcesContent":["import { DifferenceStreamWriter, LinearUnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport type { IStreamBuilder, PipedOperator } from '../types.js'\nimport type { MultiSet } from '../multiset.js'\n\n/**\n * Operator that negates the multiplicities in the input stream\n */\nexport class NegateOperator<T> extends LinearUnaryOperator<T, T> {\n inner(collection: MultiSet<T>): MultiSet<T> {\n return collection.negate()\n }\n}\n\n/**\n * Negates the multiplicities in the input stream\n */\nexport function negate<T>(): PipedOperator<T, T> {\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n const output = new StreamBuilder<T>(\n stream.graph,\n new DifferenceStreamWriter<T>(),\n )\n const operator = new NegateOperator<T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":["LinearUnaryOperator","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;AAQO,MAAM,uBAA0BA,MAAAA,oBAA0B;AAAA,EAC/D,MAAM,YAAsC;AAC1C,WAAO,WAAW,OAAA;AAAA,EACpB;AACF;AAKO,SAAS,SAAiC;AAC/C,SAAO,CAAC,WAAiD;AACvD,UAAM,SAAS,IAAIC,GAAAA;AAAAA,MACjB,OAAO;AAAA,MACP,IAAIC,MAAAA,uBAAA;AAAA,IAA0B;AAEhC,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,IAAA;AAET,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orderBy.cjs","sources":["../../../src/operators/orderBy.ts"],"sourcesContent":["import { topK, topKWithIndex } from
|
|
1
|
+
{"version":3,"file":"orderBy.cjs","sources":["../../../src/operators/orderBy.ts"],"sourcesContent":["import { topK, topKWithIndex } from './topK.js'\nimport { topKWithFractionalIndex } from './topKWithFractionalIndex.js'\nimport { map } from './map.js'\nimport { innerJoin } from './join.js'\nimport { consolidate } from './consolidate.js'\nimport type { IStreamBuilder, KeyValue } from '../types.js'\n\nexport interface OrderByOptions<Ve> {\n comparator?: (a: Ve, b: Ve) => number\n limit?: number\n offset?: number\n}\n\ntype OrderByWithFractionalIndexOptions<Ve> = OrderByOptions<Ve> & {\n setSizeCallback?: (getSize: () => number) => void\n setWindowFn?: (\n windowFn: (options: { offset?: number; limit?: number }) => void,\n ) => void\n}\n\n/**\n * Orders the elements and limits the number of results, with optional offset\n * This requires a keyed stream, and uses the `topK` operator to order all the elements.\n *\n * @param valueExtractor - A function that extracts the value to order by from the element\n * @param options - An optional object containing comparator, limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function orderBy<T extends KeyValue<unknown, unknown>, Ve = unknown>(\n valueExtractor: (\n value: T extends KeyValue<unknown, infer V> ? V : never,\n ) => Ve,\n options?: OrderByOptions<Ve>,\n) {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n const comparator =\n options?.comparator ??\n ((a, b) => {\n // Default to JS like ordering\n if (a === b) return 0\n if (a < b) return -1\n return 1\n })\n\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n type KeyType = T extends KeyValue<infer K, unknown> ? K : never\n\n return stream.pipe(\n map(\n ([key, value]) =>\n [\n null,\n [\n key,\n valueExtractor(\n value as T extends KeyValue<unknown, infer V> ? V : never,\n ),\n ],\n ] as KeyValue<null, [KeyType, Ve]>,\n ),\n topK((a, b) => comparator(a[1], b[1]), { limit, offset }),\n map(([_, [key]]) => [key, null] as KeyValue<KeyType, null>),\n innerJoin(stream),\n map(([key, value]) => {\n return [key, value[1]] as T\n }),\n consolidate(),\n )\n }\n}\n\n/**\n * Orders the elements and limits the number of results, with optional offset and\n * annotates the value with the index.\n * This requires a keyed stream, and uses the `topKWithIndex` operator to order all the elements.\n *\n * @param valueExtractor - A function that extracts the value to order by from the element\n * @param options - An optional object containing comparator, limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function orderByWithIndex<\n T extends KeyValue<unknown, unknown>,\n Ve = unknown,\n>(\n valueExtractor: (\n value: T extends KeyValue<unknown, infer V> ? V : never,\n ) => Ve,\n options?: OrderByOptions<Ve>,\n) {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n const comparator =\n options?.comparator ??\n ((a, b) => {\n // Default to JS like ordering\n if (a === b) return 0\n if (a < b) return -1\n return 1\n })\n\n return (\n stream: IStreamBuilder<T>,\n ): IStreamBuilder<\n KeyValue<\n T extends KeyValue<infer K, unknown> ? K : never,\n [T extends KeyValue<unknown, infer V> ? V : never, number]\n >\n > => {\n type KeyType = T extends KeyValue<infer K, unknown> ? K : never\n type ValueType = T extends KeyValue<unknown, infer V> ? V : never\n\n return stream.pipe(\n map(\n ([key, value]) =>\n [\n null,\n [\n key,\n valueExtractor(\n value as T extends KeyValue<unknown, infer V> ? V : never,\n ),\n ],\n ] as KeyValue<null, [KeyType, Ve]>,\n ),\n topKWithIndex((a, b) => comparator(a[1], b[1]), { limit, offset }),\n map(([_, [[key], index]]) => [key, index] as KeyValue<KeyType, number>),\n innerJoin(stream),\n map(([key, [index, value]]) => {\n return [key, [value, index]] as KeyValue<KeyType, [ValueType, number]>\n }),\n consolidate(),\n )\n }\n}\n\nexport function orderByWithFractionalIndexBase<\n T extends KeyValue<unknown, unknown>,\n Ve = unknown,\n>(\n topKFunction: typeof topKWithFractionalIndex,\n valueExtractor: (\n value: T extends KeyValue<unknown, infer V> ? V : never,\n ) => Ve,\n options?: OrderByWithFractionalIndexOptions<Ve>,\n) {\n type KeyType = T extends KeyValue<infer K, unknown> ? K : never\n type ValueType = T extends KeyValue<unknown, infer V> ? V : never\n\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n const setSizeCallback = options?.setSizeCallback\n const setWindowFn = options?.setWindowFn\n const comparator =\n options?.comparator ??\n ((a, b) => {\n // Default to JS like ordering\n if (a === b) return 0\n if (a < b) return -1\n return 1\n })\n\n return (\n stream: IStreamBuilder<T>,\n ): IStreamBuilder<[KeyType, [ValueType, string]]> => {\n return stream.pipe(\n topKFunction(\n (a: ValueType, b: ValueType) =>\n comparator(valueExtractor(a), valueExtractor(b)),\n {\n limit,\n offset,\n setSizeCallback,\n setWindowFn,\n },\n ),\n consolidate(),\n )\n }\n}\n\n/**\n * Orders the elements and limits the number of results, with optional offset and\n * annotates the value with a fractional index.\n * This requires a keyed stream, and uses the `topKWithFractionalIndex` operator to order all the elements.\n *\n * @param valueExtractor - A function that extracts the value to order by from the element\n * @param options - An optional object containing comparator, limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function orderByWithFractionalIndex<\n T extends KeyValue<unknown, unknown>,\n Ve = unknown,\n>(\n valueExtractor: (\n value: T extends KeyValue<unknown, infer V> ? V : never,\n ) => Ve,\n options?: OrderByWithFractionalIndexOptions<Ve>,\n) {\n return orderByWithFractionalIndexBase(\n topKWithFractionalIndex,\n valueExtractor,\n options,\n )\n}\n"],"names":["map","topK","innerJoin","consolidate","topKWithIndex","topKWithFractionalIndex"],"mappings":";;;;;;;AA4BO,SAAS,QACd,gBAGA,SACA;AACA,QAAM,QAAQ,SAAS,SAAS;AAChC,QAAM,SAAS,SAAS,UAAU;AAClC,QAAM,aACJ,SAAS,eACR,CAAC,GAAG,MAAM;AAET,QAAI,MAAM,EAAG,QAAO;AACpB,QAAI,IAAI,EAAG,QAAO;AAClB,WAAO;AAAA,EACT;AAEF,SAAO,CAAC,WAAiD;AAGvD,WAAO,OAAO;AAAA,MACZA,IAAAA;AAAAA,QACE,CAAC,CAAC,KAAK,KAAK,MACV;AAAA,UACE;AAAA,UACA;AAAA,YACE;AAAA,YACA;AAAA,cACE;AAAA,YAAA;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,MAEJC,KAAAA,KAAK,CAAC,GAAG,MAAM,WAAW,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,OAAO,QAAQ;AAAA,MACxDD,QAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,IAA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AAS;AAC7B,QAAM,aACJ,SAAS,eACR,CAAC,GAAG,MAAM;AAET,QAAI,MAAM,EAAG,QAAO;AACpB,QAAI,IAAI,EAAG,QAAO;AAClB,WAAO;AAAA,EACT;AAEF,SAAO,CACL,WACmD;AACnD,WAAO,OAAO;AAAA,MACZ;AAAA,QACE,CAAC,GAAc,MACb,WAAW,eAAe,CAAC,GAAG,eAAe,CAAC,CAAC;AAAA,QACjD;AAAA,UACE;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QAAA;AAAA,MACF;AAAA,MAEFA,YAAAA,YAAA;AAAA,IAAY;AAAA,EAEhB;AACF;AAWO,SAAS,2BAId,gBAGA,SACA;AACA,SAAO;AAAA,IACLE,wBAAAA;AAAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output.cjs","sources":["../../../src/operators/output.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from
|
|
1
|
+
{"version":3,"file":"output.cjs","sources":["../../../src/operators/output.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport type { IStreamBuilder, PipedOperator } from '../types.js'\nimport type { DifferenceStreamReader } from '../graph.js'\nimport type { MultiSet } from '../multiset.js'\n\n/**\n * Operator that outputs the messages in the stream\n */\nexport class OutputOperator<T> extends UnaryOperator<T> {\n #fn: (data: MultiSet<T>) => void\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<T>,\n outputWriter: DifferenceStreamWriter<T>,\n fn: (data: MultiSet<T>) => void,\n ) {\n super(id, inputA, outputWriter)\n this.#fn = fn\n }\n\n run(): void {\n for (const message of this.inputMessages()) {\n this.#fn(message)\n this.output.sendData(message)\n }\n }\n}\n\n/**\n * Outputs the messages in the stream\n * @param fn - The function to call with each message\n */\nexport function output<T>(\n fn: (data: MultiSet<T>) => void,\n): PipedOperator<T, T> {\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n const outputStream = new StreamBuilder<T>(\n stream.graph,\n new DifferenceStreamWriter<T>(),\n )\n const operator = new OutputOperator<T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n outputStream.writer,\n fn,\n )\n stream.graph.addOperator(operator)\n return outputStream\n }\n}\n"],"names":["UnaryOperator","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;AASO,MAAM,uBAA0BA,MAAAA,cAAiB;AAAA,EACtD;AAAA,EAEA,YACE,IACA,QACA,cACA,IACA;AACA,UAAM,IAAI,QAAQ,YAAY;AAC9B,SAAK,MAAM;AAAA,EACb;AAAA,EAEA,MAAY;AACV,eAAW,WAAW,KAAK,iBAAiB;AAC1C,WAAK,IAAI,OAAO;AAChB,WAAK,OAAO,SAAS,OAAO;AAAA,IAC9B;AAAA,EACF;AACF;AAMO,SAAS,OACd,IACqB;AACrB,SAAO,CAAC,WAAiD;AACvD,UAAM,eAAe,IAAIC,GAAAA;AAAAA,MACvB,OAAO;AAAA,MACP,IAAIC,MAAAA,uBAAA;AAAA,IAA0B;AAEhC,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,aAAa;AAAA,MACb;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipe.cjs","sources":["../../../src/operators/pipe.ts"],"sourcesContent":["import type { IStreamBuilder, PipedOperator } from
|
|
1
|
+
{"version":3,"file":"pipe.cjs","sources":["../../../src/operators/pipe.ts"],"sourcesContent":["import type { IStreamBuilder, PipedOperator } from '../types.js'\n\n// Don't judge, this is the only way to type this function.\n// rxjs has very similar code to type its pipe function\n// https://github.com/ReactiveX/rxjs/blob/master/packages/rxjs/src/internal/util/pipe.ts\n// We go to 20 operators deep, because surely that's enough for anyone...\n// A user can always split the pipe into multiple pipes to get around this.\nexport function pipe<T, O>(o1: PipedOperator<T, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, T10>, o10: PipedOperator<T10, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, T10>, o10: PipedOperator<T10, T11>, o11: PipedOperator<T11, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, T10>, o10: PipedOperator<T10, T11>, o11: PipedOperator<T11, T12>, o12: PipedOperator<T12, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, T10>, o10: PipedOperator<T10, T11>, o11: PipedOperator<T11, T12>, o12: PipedOperator<T12, T13>, o13: PipedOperator<T13, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, T10>, o10: PipedOperator<T10, T11>, o11: PipedOperator<T11, T12>, o12: PipedOperator<T12, T13>, o13: PipedOperator<T13, T14>, o14: PipedOperator<T14, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, T10>, o10: PipedOperator<T10, T11>, o11: PipedOperator<T11, T12>, o12: PipedOperator<T12, T13>, o13: PipedOperator<T13, T14>, o14: PipedOperator<T14, T15>, o15: PipedOperator<T15, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, T10>, o10: PipedOperator<T10, T11>, o11: PipedOperator<T11, T12>, o12: PipedOperator<T12, T13>, o13: PipedOperator<T13, T14>, o14: PipedOperator<T14, T15>, o15: PipedOperator<T15, T16>, o16: PipedOperator<T16, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, T10>, o10: PipedOperator<T10, T11>, o11: PipedOperator<T11, T12>, o12: PipedOperator<T12, T13>, o13: PipedOperator<T13, T14>, o14: PipedOperator<T14, T15>, o15: PipedOperator<T15, T16>, o16: PipedOperator<T16, T17>, o17: PipedOperator<T17, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, T10>, o10: PipedOperator<T10, T11>, o11: PipedOperator<T11, T12>, o12: PipedOperator<T12, T13>, o13: PipedOperator<T13, T14>, o14: PipedOperator<T14, T15>, o15: PipedOperator<T15, T16>, o16: PipedOperator<T16, T17>, o17: PipedOperator<T17, T18>, o18: PipedOperator<T18, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, T10>, o10: PipedOperator<T10, T11>, o11: PipedOperator<T11, T12>, o12: PipedOperator<T12, T13>, o13: PipedOperator<T13, T14>, o14: PipedOperator<T14, T15>, o15: PipedOperator<T15, T16>, o16: PipedOperator<T16, T17>, o17: PipedOperator<T17, T18>, o18: PipedOperator<T18, T19>, o19: PipedOperator<T19, O>): PipedOperator<T, O>\n// prettier-ignore\nexport function pipe<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, O>(o1: PipedOperator<T, T2>, o2: PipedOperator<T2, T3>, o3: PipedOperator<T3, T4>, o4: PipedOperator<T4, T5>, o5: PipedOperator<T5, T6>, o6: PipedOperator<T6, T7>, o7: PipedOperator<T7, T8>, o8: PipedOperator<T8, T9>, o9: PipedOperator<T9, T10>, o10: PipedOperator<T10, T11>, o11: PipedOperator<T11, T12>, o12: PipedOperator<T12, T13>, o13: PipedOperator<T13, T14>, o14: PipedOperator<T14, T15>, o15: PipedOperator<T15, T16>, o16: PipedOperator<T16, T17>, o17: PipedOperator<T17, T18>, o18: PipedOperator<T18, T19>, o19: PipedOperator<T19, T20>, o20: PipedOperator<T20, O>): PipedOperator<T, O>\n\n/**\n * Creates a new stream by piping the input stream through a series of operators\n */\nexport function pipe<T>(...operators: Array<PipedOperator<any, any>>) {\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n return stream.pipe(...operators)\n }\n}\n"],"names":[],"mappings":";;AAkDO,SAAS,QAAW,WAA2C;AACpE,SAAO,CAAC,WAAiD;AACvD,WAAO,OAAO,KAAK,GAAG,SAAS;AAAA,EACjC;AACF;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reduce.cjs","sources":["../../../src/operators/reduce.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from
|
|
1
|
+
{"version":3,"file":"reduce.cjs","sources":["../../../src/operators/reduce.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport { MultiSet } from '../multiset.js'\nimport { Index } from '../indexes.js'\nimport type { DifferenceStreamReader } from '../graph.js'\nimport type { IStreamBuilder, KeyValue } from '../types.js'\n\n/**\n * Base operator for reduction operations (version-free)\n */\nexport class ReduceOperator<K, V1, V2> extends UnaryOperator<[K, V1], [K, V2]> {\n #index = new Index<K, V1>()\n #indexOut = new Index<K, V2>()\n #f: (values: Array<[V1, number]>) => Array<[V2, number]>\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, V1]>,\n output: DifferenceStreamWriter<[K, V2]>,\n f: (values: Array<[V1, number]>) => Array<[V2, number]>,\n ) {\n super(id, inputA, output)\n this.#f = f\n }\n\n run(): void {\n // Collect all input messages and update the index\n const keysTodo = new Set<K>()\n for (const message of this.inputMessages()) {\n for (const [item, multiplicity] of message.getInner()) {\n const [key, value] = item\n this.#index.addValue(key, [value, multiplicity])\n keysTodo.add(key)\n }\n }\n\n // For each key, compute the reduction and delta\n const result: Array<[[K, V2], number]> = []\n for (const key of keysTodo) {\n const curr = this.#index.get(key)\n const currOut = this.#indexOut.get(key)\n const out = this.#f(curr)\n\n // Create maps for current and previous outputs using values directly as keys\n const newOutputMap = new Map<V2, number>()\n const oldOutputMap = new Map<V2, number>()\n\n // Process new output\n for (const [value, multiplicity] of out) {\n const existing = newOutputMap.get(value) ?? 0\n newOutputMap.set(value, existing + multiplicity)\n }\n\n // Process previous output\n for (const [value, multiplicity] of currOut) {\n const existing = oldOutputMap.get(value) ?? 0\n oldOutputMap.set(value, existing + multiplicity)\n }\n\n // First, emit removals for old values that are no longer present\n for (const [value, multiplicity] of oldOutputMap) {\n if (!newOutputMap.has(value)) {\n // Remove the old value entirely\n result.push([[key, value], -multiplicity])\n this.#indexOut.addValue(key, [value, -multiplicity])\n }\n }\n\n // Then, emit additions for new values that are not present in old\n for (const [value, multiplicity] of newOutputMap) {\n if (!oldOutputMap.has(value)) {\n // Add the new value only if it has non-zero multiplicity\n if (multiplicity !== 0) {\n result.push([[key, value], multiplicity])\n this.#indexOut.addValue(key, [value, multiplicity])\n }\n }\n }\n\n // Finally, emit multiplicity changes for values that were present and are still present\n for (const [value, newMultiplicity] of newOutputMap) {\n const oldMultiplicity = oldOutputMap.get(value)\n if (oldMultiplicity !== undefined) {\n const delta = newMultiplicity - oldMultiplicity\n // Only emit actual changes, i.e. non-zero deltas\n if (delta !== 0) {\n result.push([[key, value], delta])\n this.#indexOut.addValue(key, [value, delta])\n }\n }\n }\n }\n\n if (result.length > 0) {\n this.output.sendData(new MultiSet(result))\n }\n }\n}\n\n/**\n * Reduces the elements in the stream by key (version-free)\n */\nexport function reduce<\n KType extends T extends KeyValue<infer K, infer _V> ? K : never,\n V1Type extends T extends KeyValue<KType, infer V> ? V : never,\n R,\n T,\n>(f: (values: Array<[V1Type, number]>) => Array<[R, number]>) {\n return (stream: IStreamBuilder<T>): IStreamBuilder<KeyValue<KType, R>> => {\n const output = new StreamBuilder<KeyValue<KType, R>>(\n stream.graph,\n new DifferenceStreamWriter<KeyValue<KType, R>>(),\n )\n const operator = new ReduceOperator<KType, V1Type, R>(\n stream.graph.getNextOperatorId(),\n stream.connectReader() as DifferenceStreamReader<KeyValue<KType, V1Type>>,\n output.writer,\n f,\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":["UnaryOperator","Index","MultiSet","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;;;AAUO,MAAM,uBAAkCA,MAAAA,cAAgC;AAAA,EAC7E,SAAS,IAAIC,QAAAA,MAAA;AAAA,EACb,YAAY,IAAIA,QAAAA,MAAA;AAAA,EAChB;AAAA,EAEA,YACE,IACA,QACA,QACA,GACA;AACA,UAAM,IAAI,QAAQ,MAAM;AACxB,SAAK,KAAK;AAAA,EACZ;AAAA,EAEA,MAAY;A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QACF;AAAA,MACF;AAGA,iBAAW,CAAC,OAAO,eAAe,KAAK,cAAc;AACnD,cAAM,kBAAkB,aAAa,IAAI,KAAK;AAC9C,YAAI,oBAAoB,QAAW;AACjC,gBAAM,QAAQ,kBAAkB;AAEhC,cAAI,UAAU,GAAG;AACf,mBAAO,KAAK,CAAC,CAAC,KAAK,KAAK,GAAG,KAAK,CAAC;AACjC,iBAAK,UAAU,SAAS,KAAK,CAAC,OAAO,KAAK,CAAC;AAAA,UAC7C;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,QAAI,OAAO,SAAS,GAAG;AACrB,WAAK,OAAO,SAAS,IAAIC,SAAAA,SAAS,MAAM,CAAC;AAAA,IAC3C;AAAA,EACF;AACF;AAKO,SAAS,OAKd,GAA4D;AAC5D,SAAO,CAAC,WAAkE;AACxE,UAAM,SAAS,IAAIC,GAAAA;AAAAA,MACjB,OAAO;AAAA,MACP,IAAIC,MAAAA,uBAAA;AAAA,IAA2C;AAEjD,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tap.cjs","sources":["../../../src/operators/tap.ts"],"sourcesContent":["import { DifferenceStreamWriter, LinearUnaryOperator } from
|
|
1
|
+
{"version":3,"file":"tap.cjs","sources":["../../../src/operators/tap.ts"],"sourcesContent":["import { DifferenceStreamWriter, LinearUnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport type { IStreamBuilder, PipedOperator } from '../types.js'\nimport type { DifferenceStreamReader } from '../graph.js'\nimport type { MultiSet } from '../multiset.js'\n\n/**\n * Operator that applies a function to each multi-set in the input stream\n */\nexport class TapOperator<T> extends LinearUnaryOperator<T, T> {\n #f: (data: MultiSet<T>) => void\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<T>,\n output: DifferenceStreamWriter<T>,\n f: (data: MultiSet<T>) => void,\n ) {\n super(id, inputA, output)\n this.#f = f\n }\n\n inner(collection: MultiSet<T>): MultiSet<T> {\n this.#f(collection)\n return collection\n }\n}\n\n/**\n * Invokes a function for each multi-set in the input stream.\n * This operator doesn't modify the stream and is used to perform side effects.\n * @param f - The function to invoke on each multi-set\n * @returns The input stream\n */\nexport function tap<T>(f: (data: MultiSet<T>) => void): PipedOperator<T, T> {\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n const output = new StreamBuilder<T>(\n stream.graph,\n new DifferenceStreamWriter<T>(),\n )\n const operator = new TapOperator<T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n f,\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":["LinearUnaryOperator","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;AASO,MAAM,oBAAuBA,MAAAA,oBAA0B;AAAA,EAC5D;AAAA,EAEA,YACE,IACA,QACA,QACA,GACA;AACA,UAAM,IAAI,QAAQ,MAAM;AACxB,SAAK,KAAK;AAAA,EACZ;AAAA,EAEA,MAAM,YAAsC;AAC1C,SAAK,GAAG,UAAU;AAClB,WAAO;AAAA,EACT;AACF;AAQO,SAAS,IAAO,GAAqD;AAC1E,SAAO,CAAC,WAAiD;AACvD,UAAM,SAAS,IAAIC,GAAAA;AAAAA,MACjB,OAAO;AAAA,MACP,IAAIC,MAAAA,uBAAA;AAAA,IAA0B;AAEhC,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"topK.cjs","sources":["../../../src/operators/topK.ts"],"sourcesContent":["import { MultiSet } from
|
|
1
|
+
{"version":3,"file":"topK.cjs","sources":["../../../src/operators/topK.ts"],"sourcesContent":["import { MultiSet } from '../multiset.js'\nimport { reduce } from './reduce.js'\nimport type { IStreamBuilder, KeyValue, PipedOperator } from '../types'\n\ninterface TopKOptions {\n limit?: number\n offset?: number\n}\n\n/**\n * Limits the number of results based on a comparator, with optional offset.\n * This works on a keyed stream, where the key is the first element of the tuple\n * The ordering is withing a key group, i.e. elements are sorted within a key group\n * and the limit + offset is applied to that sorted group.\n * To order the entire stream, key by the same value for all elements such as null.\n *\n * @param comparator - A function that compares two elements\n * @param options - An optional object containing limit and offset properties\n * @returns A piped operator that limits the number of results\n */\nexport function topK<\n KType extends T extends KeyValue<infer K, infer _V> ? K : never,\n V1Type extends T extends KeyValue<KType, infer V> ? V : never,\n T,\n>(\n comparator: (a: V1Type, b: V1Type) => number,\n options?: TopKOptions,\n): PipedOperator<T, T> {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n const reduced = stream.pipe(\n reduce((values) => {\n // `values` is a list of tuples, first element is the value, second is the multiplicity\n const consolidated = new MultiSet(values).consolidate()\n const sortedValues = consolidated\n .getInner()\n .sort((a, b) => comparator(a[0] as V1Type, b[0] as V1Type))\n return sortedValues.slice(offset, offset + limit)\n }),\n )\n return reduced as IStreamBuilder<T>\n }\n}\n\n/**\n * Limits the number of results based on a comparator, with optional offset.\n * This works on a keyed stream, where the key is the first element of the tuple\n * The ordering is withing a key group, i.e. elements are sorted within a key group\n * and the limit + offset is applied to that sorted group.\n * To order the entire stream, key by the same value for all elements such as null.\n * Adds the index of the element to the result as [key, [value, index]]\n *\n * @param comparator - A function that compares two elements\n * @param options - An optional object containing limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function topKWithIndex<\n KType extends T extends KeyValue<infer K, infer _V> ? K : never,\n V1Type extends T extends KeyValue<KType, infer V> ? V : never,\n T,\n>(\n comparator: (a: V1Type, b: V1Type) => number,\n options?: TopKOptions,\n): PipedOperator<T, KeyValue<KType, [V1Type, number]>> {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n\n return (\n stream: IStreamBuilder<T>,\n ): IStreamBuilder<KeyValue<KType, [V1Type, number]>> => {\n const reduced = stream.pipe(\n reduce<KType, V1Type, [V1Type, number], T>((values) => {\n // `values` is a list of tuples, first element is the value, second is the multiplicity\n const consolidated = new MultiSet(values).consolidate()\n let i = offset\n const sortedValues = consolidated\n .getInner()\n .sort((a, b) => comparator(a[0], b[0]))\n .slice(offset, offset + limit)\n .map(([value, multiplicity]): [[V1Type, number], number] => [\n [value, i++],\n multiplicity,\n ])\n return sortedValues\n }),\n )\n return reduced\n }\n}\n"],"names":["reduce","MultiSet"],"mappings":";;;;AAoBO,SAAS,KAKd,YACA,SACqB;AACrB,QAAM,QAAQ,SAAS,SAAS;AAChC,QAAM,SAAS,SAAS,UAAU;AAElC,SAAO,CAAC,WAAiD;AACvD,UAAM,UAAU,OAAO;AAAA,MACrBA,OAAAA,OAAO,CAAC,WAAW;AAEjB,cAAM,eAAe,IAAIC,SAAAA,SAAS,MAAM,EAAE,YAAA;AAC1C,cAAM,eAAe,aAClB,SAAA,EACA,KAAK,CAAC,GAAG,MAAM,WAAW,EAAE,CAAC,GAAa,EAAE,CAAC,CAAW,CAAC;AAC5D,eAAO,aAAa,MAAM,QAAQ,SAAS,KAAK;AAAA,MAClD,CAAC;AAAA,IAAA;AAEH,WAAO;AAAA,EACT;AACF;AAcO,SAAS,cAKd,YACA,SACqD;AACrD,QAAM,QAAQ,SAAS,SAAS;AAChC,QAAM,SAAS,SAAS,UAAU;AAElC,SAAO,CACL,WACsD;AACtD,UAAM,UAAU,OAAO;AAAA,MACrBD,OAAAA,OAA2C,CAAC,WAAW;AAErD,cAAM,eAAe,IAAIC,SAAAA,SAAS,MAAM,EAAE,YAAA;AAC1C,YAAI,IAAI;AACR,cAAM,eAAe,aAClB,SAAA,EACA,KAAK,CAAC,GAAG,MAAM,WAAW,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EACrC,MAAM,QAAQ,SAAS,KAAK,EAC5B,IAAI,CAAC,CAAC,OAAO,YAAY,MAAkC;AAAA,UAC1D,CAAC,OAAO,GAAG;AAAA,UACX;AAAA,QAAA,CACD;AACH,eAAO;AAAA,MACT,CAAC;AAAA,IAAA;AAEH,WAAO;AAAA,EACT;AACF;;;"}
|
|
@@ -120,22 +120,18 @@ class TopKWithFractionalIndexOperator extends graph.UnaryOperator {
|
|
|
120
120
|
/**
|
|
121
121
|
* topK data structure that supports insertions and deletions
|
|
122
122
|
* and returns changes to the topK.
|
|
123
|
+
* Elements are stored as [key, value] tuples for stable tie-breaking.
|
|
123
124
|
*/
|
|
124
125
|
#topK;
|
|
125
126
|
constructor(id, inputA, output, comparator, options) {
|
|
126
127
|
super(id, inputA, output);
|
|
127
128
|
const limit = options.limit ?? Infinity;
|
|
128
129
|
const offset = options.offset ?? 0;
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
const tieBreakerA = getTag(a);
|
|
135
|
-
const tieBreakerB = getTag(b);
|
|
136
|
-
return tieBreakerA - tieBreakerB;
|
|
137
|
-
};
|
|
138
|
-
this.#topK = this.createTopK(offset, limit, compareTaggedValues);
|
|
130
|
+
this.#topK = this.createTopK(
|
|
131
|
+
offset,
|
|
132
|
+
limit,
|
|
133
|
+
createKeyedComparator(comparator)
|
|
134
|
+
);
|
|
139
135
|
options.setSizeCallback?.(() => this.#topK.size);
|
|
140
136
|
options.setWindowFn?.(this.moveTopK.bind(this));
|
|
141
137
|
}
|
|
@@ -179,11 +175,9 @@ class TopKWithFractionalIndexOperator extends graph.UnaryOperator {
|
|
|
179
175
|
moveOut: null
|
|
180
176
|
};
|
|
181
177
|
if (oldMultiplicity <= 0 && newMultiplicity > 0) {
|
|
182
|
-
|
|
183
|
-
res = this.#topK.insert(taggedValue);
|
|
178
|
+
res = this.#topK.insert([key, value]);
|
|
184
179
|
} else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
|
|
185
|
-
|
|
186
|
-
res = this.#topK.delete(taggedValue);
|
|
180
|
+
res = this.#topK.delete([key, value]);
|
|
187
181
|
} else ;
|
|
188
182
|
this.handleMoveIn(res.moveIn, result);
|
|
189
183
|
this.handleMoveOut(res.moveOut, result);
|
|
@@ -191,20 +185,14 @@ class TopKWithFractionalIndexOperator extends graph.UnaryOperator {
|
|
|
191
185
|
}
|
|
192
186
|
handleMoveIn(moveIn, result) {
|
|
193
187
|
if (moveIn) {
|
|
194
|
-
const index =
|
|
195
|
-
|
|
196
|
-
const k = getKey(taggedValue);
|
|
197
|
-
const val = getVal(taggedValue);
|
|
198
|
-
result.push([[k, [val, index]], 1]);
|
|
188
|
+
const [[key, value], index] = moveIn;
|
|
189
|
+
result.push([[key, [value, index]], 1]);
|
|
199
190
|
}
|
|
200
191
|
}
|
|
201
192
|
handleMoveOut(moveOut, result) {
|
|
202
193
|
if (moveOut) {
|
|
203
|
-
const index =
|
|
204
|
-
|
|
205
|
-
const k = getKey(taggedValue);
|
|
206
|
-
const val = getVal(taggedValue);
|
|
207
|
-
result.push([[k, [val, index]], -1]);
|
|
194
|
+
const [[key, value], index] = moveOut;
|
|
195
|
+
result.push([[key, [value, index]], -1]);
|
|
208
196
|
}
|
|
209
197
|
}
|
|
210
198
|
getMultiplicity(key) {
|
|
@@ -248,17 +236,14 @@ function getValue(indexedVal) {
|
|
|
248
236
|
function getIndex(indexedVal) {
|
|
249
237
|
return indexedVal[1];
|
|
250
238
|
}
|
|
251
|
-
function
|
|
252
|
-
return [
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
}
|
|
260
|
-
function getTag(tieBreakerTaggedValue) {
|
|
261
|
-
return tieBreakerTaggedValue[2];
|
|
239
|
+
function createKeyedComparator(comparator) {
|
|
240
|
+
return ([aKey, aVal], [bKey, bVal]) => {
|
|
241
|
+
const valueComparison = comparator(aVal, bVal);
|
|
242
|
+
if (valueComparison !== 0) {
|
|
243
|
+
return valueComparison;
|
|
244
|
+
}
|
|
245
|
+
return utils.compareKeys(aKey, bKey);
|
|
246
|
+
};
|
|
262
247
|
}
|
|
263
248
|
exports.TopKWithFractionalIndexOperator = TopKWithFractionalIndexOperator;
|
|
264
249
|
exports.getIndex = getIndex;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"topKWithFractionalIndex.cjs","sources":["../../../src/operators/topKWithFractionalIndex.ts"],"sourcesContent":["import { generateKeyBetween } from \"fractional-indexing\"\nimport { DifferenceStreamWriter, UnaryOperator } from \"../graph.js\"\nimport { StreamBuilder } from \"../d2.js\"\nimport { MultiSet } from \"../multiset.js\"\nimport {\n binarySearch,\n diffHalfOpen,\n globalObjectIdGenerator,\n} from \"../utils.js\"\nimport type { HRange } from \"../utils.js\"\nimport type { DifferenceStreamReader } from \"../graph.js\"\nimport type { IStreamBuilder, PipedOperator } from \"../types.js\"\n\nexport interface TopKWithFractionalIndexOptions {\n limit?: number\n offset?: number\n setSizeCallback?: (getSize: () => number) => void\n setWindowFn?: (\n windowFn: (options: { offset?: number; limit?: number }) => void\n ) => void\n}\n\nexport type TopKChanges<V> = {\n /** Indicates which element moves into the topK (if any) */\n moveIn: IndexedValue<V> | null\n /** Indicates which element moves out of the topK (if any) */\n moveOut: IndexedValue<V> | null\n}\n\nexport type TopKMoveChanges<V> = {\n /** Flag that marks whether there were any changes to the topK */\n changes: boolean\n /** Indicates which elements move into the topK (if any) */\n moveIns: Array<IndexedValue<V>>\n /** Indicates which elements move out of the topK (if any) */\n moveOuts: Array<IndexedValue<V>>\n}\n\n/**\n * A topK data structure that supports insertions and deletions\n * and returns changes to the topK.\n */\nexport interface TopK<V> {\n size: number\n insert: (value: V) => TopKChanges<V>\n delete: (value: V) => TopKChanges<V>\n}\n\n/**\n * Implementation of a topK data structure.\n * Uses a sorted array internally to store the values and keeps a topK window over that array.\n * Inserts and deletes are O(n) operations because worst case an element is inserted/deleted\n * at the start of the array which causes all the elements to shift to the right/left.\n */\nclass TopKArray<V> implements TopK<V> {\n #sortedValues: Array<IndexedValue<V>> = []\n #comparator: (a: V, b: V) => number\n #topKStart: number\n #topKEnd: number\n\n constructor(\n offset: number,\n limit: number,\n comparator: (a: V, b: V) => number\n ) {\n this.#topKStart = offset\n this.#topKEnd = offset + limit\n this.#comparator = comparator\n }\n\n get size(): number {\n const offset = this.#topKStart\n const limit = this.#topKEnd - this.#topKStart\n const available = this.#sortedValues.length - offset\n return Math.max(0, Math.min(limit, available))\n }\n\n /**\n * Moves the topK window\n */\n move({\n offset,\n limit,\n }: {\n offset?: number\n limit?: number\n }): TopKMoveChanges<V> {\n const oldOffset = this.#topKStart\n const oldLimit = this.#topKEnd - this.#topKStart\n\n // `this.#topKEnd` can be `Infinity` if it has no limit\n // but `diffHalfOpen` expects a finite range\n // so we restrict it to the size of the topK if topKEnd is infinite\n const oldRange: HRange = [\n this.#topKStart,\n this.#topKEnd === Infinity ? this.#topKStart + this.size : this.#topKEnd,\n ]\n\n this.#topKStart = offset ?? oldOffset\n this.#topKEnd = this.#topKStart + (limit ?? oldLimit) // can be `Infinity` if limit is `Infinity`\n\n // Also handle `Infinity` in the newRange\n const newRange: HRange = [\n this.#topKStart,\n this.#topKEnd === Infinity\n ? Math.max(this.#topKStart + this.size, oldRange[1]) // since the new limit is Infinity we need to take everything (so we need to take the biggest (finite) topKEnd)\n : this.#topKEnd,\n ]\n const { onlyInA, onlyInB } = diffHalfOpen(oldRange, newRange)\n\n const moveIns: Array<IndexedValue<V>> = []\n onlyInB.forEach((index) => {\n const value = this.#sortedValues[index]\n if (value) {\n moveIns.push(value)\n }\n })\n\n const moveOuts: Array<IndexedValue<V>> = []\n onlyInA.forEach((index) => {\n const value = this.#sortedValues[index]\n if (value) {\n moveOuts.push(value)\n }\n })\n\n // It could be that there are changes (i.e. moveIns or moveOuts)\n // but that the collection is lazy so we don't have the data yet that needs to move in/out\n // so `moveIns` and `moveOuts` will be empty but `changes` will be true\n // this will tell the caller that it needs to run the graph to load more data\n return { moveIns, moveOuts, changes: onlyInA.length + onlyInB.length > 0 }\n }\n\n insert(value: V): TopKChanges<V> {\n const result: TopKChanges<V> = { moveIn: null, moveOut: null }\n\n // Lookup insert position\n const index = this.#findIndex(value)\n // Generate fractional index based on the fractional indices of the elements before and after it\n const indexBefore =\n index === 0 ? null : getIndex(this.#sortedValues[index - 1]!)\n const indexAfter =\n index === this.#sortedValues.length\n ? null\n : getIndex(this.#sortedValues[index]!)\n const fractionalIndex = generateKeyBetween(indexBefore, indexAfter)\n\n // Insert the value at the correct position\n const val = indexedValue(value, fractionalIndex)\n // Splice is O(n) where n = all elements in the collection (i.e. n >= k) !\n this.#sortedValues.splice(index, 0, val)\n\n // Check if the topK changed\n if (index < this.#topKEnd) {\n // The inserted element is either before the top K or within the top K\n // If it is before the top K then it moves the element that was right before the topK into the topK\n // If it is within the top K then the inserted element moves into the top K\n // In both cases the last element of the old top K now moves out of the top K\n const moveInIndex = Math.max(index, this.#topKStart)\n if (moveInIndex < this.#sortedValues.length) {\n // We actually have a topK\n // because in some cases there may not be enough elements in the array to reach the start of the topK\n // e.g. [1, 2, 3] with K = 2 and offset = 3 does not have a topK\n result.moveIn = this.#sortedValues[moveInIndex]!\n\n // We need to remove the element that falls out of the top K\n // The element that falls out of the top K has shifted one to the right\n // because of the element we inserted, so we find it at index topKEnd\n if (this.#topKEnd < this.#sortedValues.length) {\n result.moveOut = this.#sortedValues[this.#topKEnd]!\n }\n }\n }\n\n return result\n }\n\n /**\n * Deletes a value that may or may not be in the topK.\n * IMPORTANT: this assumes that the value is present in the collection\n * if it's not the case it will remove the element\n * that is on the position where the provided `value` would be.\n */\n delete(value: V): TopKChanges<V> {\n const result: TopKChanges<V> = { moveIn: null, moveOut: null }\n\n // Lookup delete position\n const index = this.#findIndex(value)\n // Remove the value at that position\n const [removedElem] = this.#sortedValues.splice(index, 1)\n\n // Check if the topK changed\n if (index < this.#topKEnd) {\n // The removed element is either before the top K or within the top K\n // If it is before the top K then the first element of the topK moves out of the topK\n // If it is within the top K then the removed element moves out of the topK\n result.moveOut = removedElem!\n if (index < this.#topKStart) {\n // The removed element is before the topK\n // so actually, the first element of the topK moves out of the topK\n // and not the element that we removed\n // The first element of the topK is now at index topKStart - 1\n // since we removed an element before the topK\n const moveOutIndex = this.#topKStart - 1\n if (moveOutIndex < this.#sortedValues.length) {\n result.moveOut = this.#sortedValues[moveOutIndex]!\n } else {\n // No value is moving out of the topK\n // because there are no elements in the topK\n result.moveOut = null\n }\n }\n\n // Since we removed an element that was before or in the topK\n // the first element after the topK moved one position to the left\n // and thus falls into the topK now\n const moveInIndex = this.#topKEnd - 1\n if (moveInIndex < this.#sortedValues.length) {\n result.moveIn = this.#sortedValues[moveInIndex]!\n }\n }\n\n return result\n }\n\n // TODO: see if there is a way to refactor the code for insert and delete in the topK above\n // because they are very similar, one is shifting the topK window to the left and the other is shifting it to the right\n // so i have the feeling there is a common pattern here and we can implement both cases using that pattern\n\n #findIndex(value: V): number {\n return binarySearch(this.#sortedValues, indexedValue(value, ``), (a, b) =>\n this.#comparator(getValue(a), getValue(b))\n )\n }\n}\n\n/**\n * Operator for fractional indexed topK operations\n * This operator maintains fractional indices for sorted elements\n * and only updates indices when elements move position\n */\nexport class TopKWithFractionalIndexOperator<K, T> extends UnaryOperator<\n [K, T],\n [K, IndexedValue<T>]\n> {\n #index: Map<K, number> = new Map() // maps keys to their multiplicity\n\n /**\n * topK data structure that supports insertions and deletions\n * and returns changes to the topK.\n */\n #topK: TopK<TaggedValue<K, T>>\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, T]>,\n output: DifferenceStreamWriter<[K, IndexedValue<T>]>,\n comparator: (a: T, b: T) => number,\n options: TopKWithFractionalIndexOptions\n ) {\n super(id, inputA, output)\n const limit = options.limit ?? Infinity\n const offset = options.offset ?? 0\n const compareTaggedValues = (\n a: TaggedValue<K, T>,\n b: TaggedValue<K, T>\n ) => {\n // First compare on the value\n const valueComparison = comparator(getVal(a), getVal(b))\n if (valueComparison !== 0) {\n return valueComparison\n }\n // If the values are equal, compare on the tag (object identity)\n const tieBreakerA = getTag(a)\n const tieBreakerB = getTag(b)\n return tieBreakerA - tieBreakerB\n }\n this.#topK = this.createTopK(offset, limit, compareTaggedValues)\n options.setSizeCallback?.(() => this.#topK.size)\n options.setWindowFn?.(this.moveTopK.bind(this))\n }\n\n protected createTopK(\n offset: number,\n limit: number,\n comparator: (a: TaggedValue<K, T>, b: TaggedValue<K, T>) => number\n ): TopK<TaggedValue<K, T>> {\n return new TopKArray(offset, limit, comparator)\n }\n\n /**\n * Moves the topK window based on the provided offset and limit.\n * Any changes to the topK are sent to the output.\n */\n moveTopK({ offset, limit }: { offset?: number; limit?: number }) {\n if (!(this.#topK instanceof TopKArray)) {\n throw new Error(\n `Cannot move B+-tree implementation of TopK with fractional index`\n )\n }\n\n const result: Array<[[K, IndexedValue<T>], number]> = []\n\n const diff = this.#topK.move({ offset, limit })\n\n diff.moveIns.forEach((moveIn) => this.handleMoveIn(moveIn, result))\n diff.moveOuts.forEach((moveOut) => this.handleMoveOut(moveOut, result))\n\n if (diff.changes) {\n // There are changes to the topK\n // it could be that moveIns and moveOuts are empty\n // because the collection is lazy, so we will run the graph again to load the data\n this.output.sendData(new MultiSet(result))\n }\n }\n\n run(): void {\n const result: Array<[[K, IndexedValue<T>], number]> = []\n for (const message of this.inputMessages()) {\n for (const [item, multiplicity] of message.getInner()) {\n const [key, value] = item\n this.processElement(key, value, multiplicity, result)\n }\n }\n\n if (result.length > 0) {\n this.output.sendData(new MultiSet(result))\n }\n }\n\n processElement(\n key: K,\n value: T,\n multiplicity: number,\n result: Array<[[K, IndexedValue<T>], number]>\n ): void {\n const { oldMultiplicity, newMultiplicity } = this.addKey(key, multiplicity)\n\n let res: TopKChanges<TaggedValue<K, T>> = {\n moveIn: null,\n moveOut: null,\n }\n if (oldMultiplicity <= 0 && newMultiplicity > 0) {\n // The value was invisible but should now be visible\n // Need to insert it into the array of sorted values\n const taggedValue = tagValue(key, value)\n res = this.#topK.insert(taggedValue)\n } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {\n // The value was visible but should now be invisible\n // Need to remove it from the array of sorted values\n const taggedValue = tagValue(key, value)\n res = this.#topK.delete(taggedValue)\n } else {\n // The value was invisible and it remains invisible\n // or it was visible and remains visible\n // so it doesn't affect the topK\n }\n\n this.handleMoveIn(res.moveIn, result)\n this.handleMoveOut(res.moveOut, result)\n\n return\n }\n\n private handleMoveIn(\n moveIn: IndexedValue<TaggedValue<K, T>> | null,\n result: Array<[[K, IndexedValue<T>], number]>\n ) {\n if (moveIn) {\n const index = getIndex(moveIn)\n const taggedValue = getValue(moveIn)\n const k = getKey(taggedValue)\n const val = getVal(taggedValue)\n result.push([[k, [val, index]], 1])\n }\n }\n\n private handleMoveOut(\n moveOut: IndexedValue<TaggedValue<K, T>> | null,\n result: Array<[[K, IndexedValue<T>], number]>\n ) {\n if (moveOut) {\n const index = getIndex(moveOut)\n const taggedValue = getValue(moveOut)\n const k = getKey(taggedValue)\n const val = getVal(taggedValue)\n result.push([[k, [val, index]], -1])\n }\n }\n\n private getMultiplicity(key: K): number {\n return this.#index.get(key) ?? 0\n }\n\n private addKey(\n key: K,\n multiplicity: number\n ): { oldMultiplicity: number; newMultiplicity: number } {\n const oldMultiplicity = this.getMultiplicity(key)\n const newMultiplicity = oldMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.#index.delete(key)\n } else {\n this.#index.set(key, newMultiplicity)\n }\n return { oldMultiplicity, newMultiplicity }\n }\n}\n\n/**\n * Limits the number of results based on a comparator, with optional offset.\n * Uses fractional indexing to minimize the number of changes when elements move positions.\n * Each element is assigned a fractional index that is lexicographically sortable.\n * When elements move, only the indices of the moved elements are updated, not all elements.\n *\n * @param comparator - A function that compares two elements\n * @param options - An optional object containing limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function topKWithFractionalIndex<KType, T>(\n comparator: (a: T, b: T) => number,\n options?: TopKWithFractionalIndexOptions\n): PipedOperator<[KType, T], [KType, IndexedValue<T>]> {\n const opts = options || {}\n\n return (\n stream: IStreamBuilder<[KType, T]>\n ): IStreamBuilder<[KType, IndexedValue<T>]> => {\n const output = new StreamBuilder<[KType, IndexedValue<T>]>(\n stream.graph,\n new DifferenceStreamWriter<[KType, IndexedValue<T>]>()\n )\n const operator = new TopKWithFractionalIndexOperator<KType, T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n comparator,\n opts\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n\n// Abstraction for fractionally indexed values\nexport type FractionalIndex = string\nexport type IndexedValue<V> = [V, FractionalIndex]\n\nexport function indexedValue<V>(\n value: V,\n index: FractionalIndex\n): IndexedValue<V> {\n return [value, index]\n}\n\nexport function getValue<V>(indexedVal: IndexedValue<V>): V {\n return indexedVal[0]\n}\n\nexport function getIndex<V>(indexedVal: IndexedValue<V>): FractionalIndex {\n return indexedVal[1]\n}\n\nexport type Tag = number\nexport type TaggedValue<K, V> = [K, V, Tag]\n\nfunction tagValue<K, V>(key: K, value: V): TaggedValue<K, V> {\n return [key, value, globalObjectIdGenerator.getId(key)]\n}\n\nfunction getKey<K, V>(tieBreakerTaggedValue: TaggedValue<K, V>): K {\n return tieBreakerTaggedValue[0]\n}\n\nfunction getVal<K, V>(tieBreakerTaggedValue: TaggedValue<K, V>): V {\n return tieBreakerTaggedValue[1]\n}\n\nfunction getTag<K, V>(tieBreakerTaggedValue: TaggedValue<K, V>): Tag {\n return tieBreakerTaggedValue[2]\n}\n"],"names":["diffHalfOpen","generateKeyBetween","binarySearch","UnaryOperator","MultiSet","StreamBuilder","DifferenceStreamWriter","globalObjectIdGenerator"],"mappings":";;;;;;;AAsDA,MAAM,UAAgC;AAAA,EACpC,gBAAwC,CAAA;AAAA,EACxC;AAAA,EACA;AAA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AAK;AACtB;AAEO,SAAS,SAAY,YAAgC;AAC1D,SAAO,WAAW,CAAC;AACrB;AAEO,SAAS,SAAY,YAA8C;AACxE,SAAO,WAAW,CAAC;AACrB;AAKA,SAAS,SAAe,KAAQ,OAA6B;AAC3D,SAAO,CAAC,KAAK,OAAOC,MAAAA,wBAAwB,MAAM,GAAG,CAAC;AACxD;AAEA,SAAS,OAAa,uBAA6C;AACjE,SAAO,sBAAsB,CAAC;AAChC;AAEA,SAAS,OAAa,uBAA6C;AACjE,SAAO,sBAAsB,CAAC;AAChC;AAEA,SAAS,OAAa,uBAA+C;AACnE,SAAO,sBAAsB,CAAC;AAChC;;;;;;"}
|
|
1
|
+
{"version":3,"file":"topKWithFractionalIndex.cjs","sources":["../../../src/operators/topKWithFractionalIndex.ts"],"sourcesContent":["import { generateKeyBetween } from 'fractional-indexing'\nimport { DifferenceStreamWriter, UnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport { MultiSet } from '../multiset.js'\nimport { binarySearch, compareKeys, diffHalfOpen } from '../utils.js'\nimport type { HRange } from '../utils.js'\nimport type { DifferenceStreamReader } from '../graph.js'\nimport type { IStreamBuilder, PipedOperator } from '../types.js'\n\nexport interface TopKWithFractionalIndexOptions {\n limit?: number\n offset?: number\n setSizeCallback?: (getSize: () => number) => void\n setWindowFn?: (\n windowFn: (options: { offset?: number; limit?: number }) => void,\n ) => void\n}\n\nexport type TopKChanges<V> = {\n /** Indicates which element moves into the topK (if any) */\n moveIn: IndexedValue<V> | null\n /** Indicates which element moves out of the topK (if any) */\n moveOut: IndexedValue<V> | null\n}\n\nexport type TopKMoveChanges<V> = {\n /** Flag that marks whether there were any changes to the topK */\n changes: boolean\n /** Indicates which elements move into the topK (if any) */\n moveIns: Array<IndexedValue<V>>\n /** Indicates which elements move out of the topK (if any) */\n moveOuts: Array<IndexedValue<V>>\n}\n\n/**\n * A topK data structure that supports insertions and deletions\n * and returns changes to the topK.\n */\nexport interface TopK<V> {\n size: number\n insert: (value: V) => TopKChanges<V>\n delete: (value: V) => TopKChanges<V>\n}\n\n/**\n * Implementation of a topK data structure.\n * Uses a sorted array internally to store the values and keeps a topK window over that array.\n * Inserts and deletes are O(n) operations because worst case an element is inserted/deleted\n * at the start of the array which causes all the elements to shift to the right/left.\n */\nclass TopKArray<V> implements TopK<V> {\n #sortedValues: Array<IndexedValue<V>> = []\n #comparator: (a: V, b: V) => number\n #topKStart: number\n #topKEnd: number\n\n constructor(\n offset: number,\n limit: number,\n comparator: (a: V, b: V) => number,\n ) {\n this.#topKStart = offset\n this.#topKEnd = offset + limit\n this.#comparator = comparator\n }\n\n get size(): number {\n const offset = this.#topKStart\n const limit = this.#topKEnd - this.#topKStart\n const available = this.#sortedValues.length - offset\n return Math.max(0, Math.min(limit, available))\n }\n\n /**\n * Moves the topK window\n */\n move({\n offset,\n limit,\n }: {\n offset?: number\n limit?: number\n }): TopKMoveChanges<V> {\n const oldOffset = this.#topKStart\n const oldLimit = this.#topKEnd - this.#topKStart\n\n // `this.#topKEnd` can be `Infinity` if it has no limit\n // but `diffHalfOpen` expects a finite range\n // so we restrict it to the size of the topK if topKEnd is infinite\n const oldRange: HRange = [\n this.#topKStart,\n this.#topKEnd === Infinity ? this.#topKStart + this.size : this.#topKEnd,\n ]\n\n this.#topKStart = offset ?? oldOffset\n this.#topKEnd = this.#topKStart + (limit ?? oldLimit) // can be `Infinity` if limit is `Infinity`\n\n // Also handle `Infinity` in the newRange\n const newRange: HRange = [\n this.#topKStart,\n this.#topKEnd === Infinity\n ? Math.max(this.#topKStart + this.size, oldRange[1]) // since the new limit is Infinity we need to take everything (so we need to take the biggest (finite) topKEnd)\n : this.#topKEnd,\n ]\n const { onlyInA, onlyInB } = diffHalfOpen(oldRange, newRange)\n\n const moveIns: Array<IndexedValue<V>> = []\n onlyInB.forEach((index) => {\n const value = this.#sortedValues[index]\n if (value) {\n moveIns.push(value)\n }\n })\n\n const moveOuts: Array<IndexedValue<V>> = []\n onlyInA.forEach((index) => {\n const value = this.#sortedValues[index]\n if (value) {\n moveOuts.push(value)\n }\n })\n\n // It could be that there are changes (i.e. moveIns or moveOuts)\n // but that the collection is lazy so we don't have the data yet that needs to move in/out\n // so `moveIns` and `moveOuts` will be empty but `changes` will be true\n // this will tell the caller that it needs to run the graph to load more data\n return { moveIns, moveOuts, changes: onlyInA.length + onlyInB.length > 0 }\n }\n\n insert(value: V): TopKChanges<V> {\n const result: TopKChanges<V> = { moveIn: null, moveOut: null }\n\n // Lookup insert position\n const index = this.#findIndex(value)\n // Generate fractional index based on the fractional indices of the elements before and after it\n const indexBefore =\n index === 0 ? null : getIndex(this.#sortedValues[index - 1]!)\n const indexAfter =\n index === this.#sortedValues.length\n ? null\n : getIndex(this.#sortedValues[index]!)\n const fractionalIndex = generateKeyBetween(indexBefore, indexAfter)\n\n // Insert the value at the correct position\n const val = indexedValue(value, fractionalIndex)\n // Splice is O(n) where n = all elements in the collection (i.e. n >= k) !\n this.#sortedValues.splice(index, 0, val)\n\n // Check if the topK changed\n if (index < this.#topKEnd) {\n // The inserted element is either before the top K or within the top K\n // If it is before the top K then it moves the element that was right before the topK into the topK\n // If it is within the top K then the inserted element moves into the top K\n // In both cases the last element of the old top K now moves out of the top K\n const moveInIndex = Math.max(index, this.#topKStart)\n if (moveInIndex < this.#sortedValues.length) {\n // We actually have a topK\n // because in some cases there may not be enough elements in the array to reach the start of the topK\n // e.g. [1, 2, 3] with K = 2 and offset = 3 does not have a topK\n result.moveIn = this.#sortedValues[moveInIndex]!\n\n // We need to remove the element that falls out of the top K\n // The element that falls out of the top K has shifted one to the right\n // because of the element we inserted, so we find it at index topKEnd\n if (this.#topKEnd < this.#sortedValues.length) {\n result.moveOut = this.#sortedValues[this.#topKEnd]!\n }\n }\n }\n\n return result\n }\n\n /**\n * Deletes a value that may or may not be in the topK.\n * IMPORTANT: this assumes that the value is present in the collection\n * if it's not the case it will remove the element\n * that is on the position where the provided `value` would be.\n */\n delete(value: V): TopKChanges<V> {\n const result: TopKChanges<V> = { moveIn: null, moveOut: null }\n\n // Lookup delete position\n const index = this.#findIndex(value)\n // Remove the value at that position\n const [removedElem] = this.#sortedValues.splice(index, 1)\n\n // Check if the topK changed\n if (index < this.#topKEnd) {\n // The removed element is either before the top K or within the top K\n // If it is before the top K then the first element of the topK moves out of the topK\n // If it is within the top K then the removed element moves out of the topK\n result.moveOut = removedElem!\n if (index < this.#topKStart) {\n // The removed element is before the topK\n // so actually, the first element of the topK moves out of the topK\n // and not the element that we removed\n // The first element of the topK is now at index topKStart - 1\n // since we removed an element before the topK\n const moveOutIndex = this.#topKStart - 1\n if (moveOutIndex < this.#sortedValues.length) {\n result.moveOut = this.#sortedValues[moveOutIndex]!\n } else {\n // No value is moving out of the topK\n // because there are no elements in the topK\n result.moveOut = null\n }\n }\n\n // Since we removed an element that was before or in the topK\n // the first element after the topK moved one position to the left\n // and thus falls into the topK now\n const moveInIndex = this.#topKEnd - 1\n if (moveInIndex < this.#sortedValues.length) {\n result.moveIn = this.#sortedValues[moveInIndex]!\n }\n }\n\n return result\n }\n\n // TODO: see if there is a way to refactor the code for insert and delete in the topK above\n // because they are very similar, one is shifting the topK window to the left and the other is shifting it to the right\n // so i have the feeling there is a common pattern here and we can implement both cases using that pattern\n\n #findIndex(value: V): number {\n return binarySearch(this.#sortedValues, indexedValue(value, ``), (a, b) =>\n this.#comparator(getValue(a), getValue(b)),\n )\n }\n}\n\n/**\n * Operator for fractional indexed topK operations\n * This operator maintains fractional indices for sorted elements\n * and only updates indices when elements move position\n */\nexport class TopKWithFractionalIndexOperator<\n K extends string | number,\n T,\n> extends UnaryOperator<[K, T], [K, IndexedValue<T>]> {\n #index: Map<K, number> = new Map() // maps keys to their multiplicity\n\n /**\n * topK data structure that supports insertions and deletions\n * and returns changes to the topK.\n * Elements are stored as [key, value] tuples for stable tie-breaking.\n */\n #topK: TopK<[K, T]>\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, T]>,\n output: DifferenceStreamWriter<[K, IndexedValue<T>]>,\n comparator: (a: T, b: T) => number,\n options: TopKWithFractionalIndexOptions,\n ) {\n super(id, inputA, output)\n const limit = options.limit ?? Infinity\n const offset = options.offset ?? 0\n this.#topK = this.createTopK(\n offset,\n limit,\n createKeyedComparator(comparator),\n )\n options.setSizeCallback?.(() => this.#topK.size)\n options.setWindowFn?.(this.moveTopK.bind(this))\n }\n\n protected createTopK(\n offset: number,\n limit: number,\n comparator: (a: [K, T], b: [K, T]) => number,\n ): TopK<[K, T]> {\n return new TopKArray(offset, limit, comparator)\n }\n\n /**\n * Moves the topK window based on the provided offset and limit.\n * Any changes to the topK are sent to the output.\n */\n moveTopK({ offset, limit }: { offset?: number; limit?: number }) {\n if (!(this.#topK instanceof TopKArray)) {\n throw new Error(\n `Cannot move B+-tree implementation of TopK with fractional index`,\n )\n }\n\n const result: Array<[[K, IndexedValue<T>], number]> = []\n\n const diff = this.#topK.move({ offset, limit })\n\n diff.moveIns.forEach((moveIn) => this.handleMoveIn(moveIn, result))\n diff.moveOuts.forEach((moveOut) => this.handleMoveOut(moveOut, result))\n\n if (diff.changes) {\n // There are changes to the topK\n // it could be that moveIns and moveOuts are empty\n // because the collection is lazy, so we will run the graph again to load the data\n this.output.sendData(new MultiSet(result))\n }\n }\n\n run(): void {\n const result: Array<[[K, IndexedValue<T>], number]> = []\n for (const message of this.inputMessages()) {\n for (const [item, multiplicity] of message.getInner()) {\n const [key, value] = item\n this.processElement(key, value, multiplicity, result)\n }\n }\n\n if (result.length > 0) {\n this.output.sendData(new MultiSet(result))\n }\n }\n\n processElement(\n key: K,\n value: T,\n multiplicity: number,\n result: Array<[[K, IndexedValue<T>], number]>,\n ): void {\n const { oldMultiplicity, newMultiplicity } = this.addKey(key, multiplicity)\n\n let res: TopKChanges<[K, T]> = {\n moveIn: null,\n moveOut: null,\n }\n if (oldMultiplicity <= 0 && newMultiplicity > 0) {\n // The value was invisible but should now be visible\n // Need to insert it into the array of sorted values\n res = this.#topK.insert([key, value])\n } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {\n // The value was visible but should now be invisible\n // Need to remove it from the array of sorted values\n res = this.#topK.delete([key, value])\n } else {\n // The value was invisible and it remains invisible\n // or it was visible and remains visible\n // so it doesn't affect the topK\n }\n\n this.handleMoveIn(res.moveIn, result)\n this.handleMoveOut(res.moveOut, result)\n\n return\n }\n\n private handleMoveIn(\n moveIn: IndexedValue<[K, T]> | null,\n result: Array<[[K, IndexedValue<T>], number]>,\n ) {\n if (moveIn) {\n const [[key, value], index] = moveIn\n result.push([[key, [value, index]], 1])\n }\n }\n\n private handleMoveOut(\n moveOut: IndexedValue<[K, T]> | null,\n result: Array<[[K, IndexedValue<T>], number]>,\n ) {\n if (moveOut) {\n const [[key, value], index] = moveOut\n result.push([[key, [value, index]], -1])\n }\n }\n\n private getMultiplicity(key: K): number {\n return this.#index.get(key) ?? 0\n }\n\n private addKey(\n key: K,\n multiplicity: number,\n ): { oldMultiplicity: number; newMultiplicity: number } {\n const oldMultiplicity = this.getMultiplicity(key)\n const newMultiplicity = oldMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.#index.delete(key)\n } else {\n this.#index.set(key, newMultiplicity)\n }\n return { oldMultiplicity, newMultiplicity }\n }\n}\n\n/**\n * Limits the number of results based on a comparator, with optional offset.\n * Uses fractional indexing to minimize the number of changes when elements move positions.\n * Each element is assigned a fractional index that is lexicographically sortable.\n * When elements move, only the indices of the moved elements are updated, not all elements.\n *\n * @param comparator - A function that compares two elements\n * @param options - An optional object containing limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function topKWithFractionalIndex<KType extends string | number, T>(\n comparator: (a: T, b: T) => number,\n options?: TopKWithFractionalIndexOptions,\n): PipedOperator<[KType, T], [KType, IndexedValue<T>]> {\n const opts = options || {}\n\n return (\n stream: IStreamBuilder<[KType, T]>,\n ): IStreamBuilder<[KType, IndexedValue<T>]> => {\n const output = new StreamBuilder<[KType, IndexedValue<T>]>(\n stream.graph,\n new DifferenceStreamWriter<[KType, IndexedValue<T>]>(),\n )\n const operator = new TopKWithFractionalIndexOperator<KType, T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n comparator,\n opts,\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n\n// Abstraction for fractionally indexed values\nexport type FractionalIndex = string\nexport type IndexedValue<V> = [V, FractionalIndex]\n\nexport function indexedValue<V>(\n value: V,\n index: FractionalIndex,\n): IndexedValue<V> {\n return [value, index]\n}\n\nexport function getValue<V>(indexedVal: IndexedValue<V>): V {\n return indexedVal[0]\n}\n\nexport function getIndex<V>(indexedVal: IndexedValue<V>): FractionalIndex {\n return indexedVal[1]\n}\n\n/**\n * Creates a comparator for [key, value] tuples that first compares values,\n * then uses the row key as a stable tie-breaker.\n */\nfunction createKeyedComparator<K extends string | number, T>(\n comparator: (a: T, b: T) => number,\n): (a: [K, T], b: [K, T]) => number {\n return ([aKey, aVal], [bKey, bVal]) => {\n // First compare on the value\n const valueComparison = comparator(aVal, bVal)\n if (valueComparison !== 0) {\n return valueComparison\n }\n // If the values are equal, use the row key as tie-breaker\n // This provides stable, deterministic ordering since keys are string | number\n return compareKeys(aKey, bKey)\n }\n}\n"],"names":["diffHalfOpen","generateKeyBetween","binarySearch","UnaryOperator","MultiSet","StreamBuilder","DifferenceStreamWriter","compareKeys"],"mappings":";;;;;;;AAkDA,MAAM,UAAgC;AAAA,EACpC,gBAAwC,CAAA;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YACE,QACA,OACA,YACA;AACA,SAAK,aAAa;AAClB,SAAK,WAAW,SAAS;AACzB,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,IAAI,OAAe;AACjB,UAAM,SAAS,KAAK;AACpB,UAAM,QAAQ,KAAK,WAAW,KAAK;AACnC,UAAM,YAAY,KAAK,cAAc,SAAS;AAC9C,WAAO,KAAK,IAAI,GAAG,KAAK,IAAI,OAAO,SAAS,CAAC;AAAA,EAC/C;AAAA;AAAA;AAAA;A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OAAO;AACL,WAAK,OAAO,IAAI,KAAK,eAAe;AAAA,IACtC;AACA,WAAO,EAAE,iBAAiB,gBAAA;AAAA,EAC5B;AACF;AAYO,SAAS,wBACd,YACA,SACqD;AACrD,QAAM,OAAO,WAAW,CAAA;AAExB,SAAO,CACL,WAC6C;AAC7C,UAAM,SAAS,IAAIC,GAAAA;AAAAA,MACjB,OAAO;AAAA,MACP,IAAIC,MAAAA,uBAAA;AAAA,IAAiD;AAEvD,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,MACA;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;AAMO,SAAS,aACd,OACA,OACiB;AACjB,SAAO,CAAC,OAAO,KAAK;AACtB;AAEO,SAAS,SAAY,YAAgC;AAC1D,SAAO,WAAW,CAAC;AACrB;AAEO,SAAS,SAAY,YAA8C;AACxE,SAAO,WAAW,CAAC;AACrB;AAMA,SAAS,sBACP,YACkC;AAClC,SAAO,CAAC,CAAC,MAAM,IAAI,GAAG,CAAC,MAAM,IAAI,MAAM;AAErC,UAAM,kBAAkB,WAAW,MAAM,IAAI;AAC7C,QAAI,oBAAoB,GAAG;AACzB,aAAO;AAAA,IACT;AAGA,WAAOC,MAAAA,YAAY,MAAM,IAAI;AAAA,EAC/B;AACF;;;;;;"}
|
|
@@ -37,16 +37,10 @@ export interface TopK<V> {
|
|
|
37
37
|
* This operator maintains fractional indices for sorted elements
|
|
38
38
|
* and only updates indices when elements move position
|
|
39
39
|
*/
|
|
40
|
-
export declare class TopKWithFractionalIndexOperator<K, T> extends UnaryOperator<[
|
|
41
|
-
K,
|
|
42
|
-
T
|
|
43
|
-
], [
|
|
44
|
-
K,
|
|
45
|
-
IndexedValue<T>
|
|
46
|
-
]> {
|
|
40
|
+
export declare class TopKWithFractionalIndexOperator<K extends string | number, T> extends UnaryOperator<[K, T], [K, IndexedValue<T>]> {
|
|
47
41
|
#private;
|
|
48
42
|
constructor(id: number, inputA: DifferenceStreamReader<[K, T]>, output: DifferenceStreamWriter<[K, IndexedValue<T>]>, comparator: (a: T, b: T) => number, options: TopKWithFractionalIndexOptions);
|
|
49
|
-
protected createTopK(offset: number, limit: number, comparator: (a:
|
|
43
|
+
protected createTopK(offset: number, limit: number, comparator: (a: [K, T], b: [K, T]) => number): TopK<[K, T]>;
|
|
50
44
|
/**
|
|
51
45
|
* Moves the topK window based on the provided offset and limit.
|
|
52
46
|
* Any changes to the topK are sent to the output.
|
|
@@ -72,11 +66,9 @@ export declare class TopKWithFractionalIndexOperator<K, T> extends UnaryOperator
|
|
|
72
66
|
* @param options - An optional object containing limit and offset properties
|
|
73
67
|
* @returns A piped operator that orders the elements and limits the number of results
|
|
74
68
|
*/
|
|
75
|
-
export declare function topKWithFractionalIndex<KType, T>(comparator: (a: T, b: T) => number, options?: TopKWithFractionalIndexOptions): PipedOperator<[KType, T], [KType, IndexedValue<T>]>;
|
|
69
|
+
export declare function topKWithFractionalIndex<KType extends string | number, T>(comparator: (a: T, b: T) => number, options?: TopKWithFractionalIndexOptions): PipedOperator<[KType, T], [KType, IndexedValue<T>]>;
|
|
76
70
|
export type FractionalIndex = string;
|
|
77
71
|
export type IndexedValue<V> = [V, FractionalIndex];
|
|
78
72
|
export declare function indexedValue<V>(value: V, index: FractionalIndex): IndexedValue<V>;
|
|
79
73
|
export declare function getValue<V>(indexedVal: IndexedValue<V>): V;
|
|
80
74
|
export declare function getIndex<V>(indexedVal: IndexedValue<V>): FractionalIndex;
|
|
81
|
-
export type Tag = number;
|
|
82
|
-
export type TaggedValue<K, V> = [K, V, Tag];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TopKWithFractionalIndexOperator, IndexedValue,
|
|
1
|
+
import { TopKWithFractionalIndexOperator, IndexedValue, TopK, TopKWithFractionalIndexOptions } from './topKWithFractionalIndex.js';
|
|
2
2
|
import { PipedOperator } from '../types.js';
|
|
3
3
|
export declare function loadBTree(): Promise<void>;
|
|
4
4
|
/**
|
|
@@ -6,8 +6,8 @@ export declare function loadBTree(): Promise<void>;
|
|
|
6
6
|
* This operator maintains fractional indices for sorted elements
|
|
7
7
|
* and only updates indices when elements move position
|
|
8
8
|
*/
|
|
9
|
-
export declare class TopKWithFractionalIndexBTreeOperator<K, T> extends TopKWithFractionalIndexOperator<K, T> {
|
|
10
|
-
protected createTopK(offset: number, limit: number, comparator: (a:
|
|
9
|
+
export declare class TopKWithFractionalIndexBTreeOperator<K extends string | number, T> extends TopKWithFractionalIndexOperator<K, T> {
|
|
10
|
+
protected createTopK(offset: number, limit: number, comparator: (a: [K, T], b: [K, T]) => number): TopK<[K, T]>;
|
|
11
11
|
}
|
|
12
12
|
/**
|
|
13
13
|
* Limits the number of results based on a comparator, with optional offset.
|
|
@@ -24,4 +24,4 @@ export declare class TopKWithFractionalIndexBTreeOperator<K, T> extends TopKWith
|
|
|
24
24
|
* @param options - An optional object containing limit and offset properties
|
|
25
25
|
* @returns A piped operator that orders the elements and limits the number of results
|
|
26
26
|
*/
|
|
27
|
-
export declare function topKWithFractionalIndexBTree<KType, T>(comparator: (a: T, b: T) => number, options?: TopKWithFractionalIndexOptions): PipedOperator<[KType, T], [KType, IndexedValue<T>]>;
|
|
27
|
+
export declare function topKWithFractionalIndexBTree<KType extends string | number, T>(comparator: (a: T, b: T) => number, options?: TopKWithFractionalIndexOptions): PipedOperator<[KType, T], [KType, IndexedValue<T>]>;
|
package/dist/cjs/utils.cjs
CHANGED
|
@@ -105,10 +105,19 @@ function range(start, end) {
|
|
|
105
105
|
for (let i = start; i < end; i++) out.push(i);
|
|
106
106
|
return out;
|
|
107
107
|
}
|
|
108
|
+
function compareKeys(a, b) {
|
|
109
|
+
if (typeof a === typeof b) {
|
|
110
|
+
if (a < b) return -1;
|
|
111
|
+
if (a > b) return 1;
|
|
112
|
+
return 0;
|
|
113
|
+
}
|
|
114
|
+
return typeof a === `string` ? -1 : 1;
|
|
115
|
+
}
|
|
108
116
|
exports.DefaultMap = DefaultMap;
|
|
109
117
|
exports.ObjectIdGenerator = ObjectIdGenerator;
|
|
110
118
|
exports.binarySearch = binarySearch;
|
|
111
119
|
exports.chunkedArrayPush = chunkedArrayPush;
|
|
120
|
+
exports.compareKeys = compareKeys;
|
|
112
121
|
exports.diffHalfOpen = diffHalfOpen;
|
|
113
122
|
exports.globalObjectIdGenerator = globalObjectIdGenerator;
|
|
114
123
|
//# sourceMappingURL=utils.cjs.map
|