@tanstack/db-ivm 0.1.25 → 0.2.0

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.
Files changed (151) hide show
  1. package/README.md +5 -6
  2. package/dist/cjs/d2.d.cts +3 -3
  3. package/dist/cjs/graph.d.cts +2 -2
  4. package/dist/cjs/hashing/hash.cjs +58 -3
  5. package/dist/cjs/hashing/hash.cjs.map +1 -1
  6. package/dist/cjs/hashing/hash.d.cts +9 -0
  7. package/dist/cjs/hashing/index.d.cts +2 -2
  8. package/dist/cjs/hashing/murmur.cjs +26 -15
  9. package/dist/cjs/hashing/murmur.cjs.map +1 -1
  10. package/dist/cjs/hashing/murmur.d.cts +2 -0
  11. package/dist/cjs/index.cjs +25 -51
  12. package/dist/cjs/index.cjs.map +1 -1
  13. package/dist/cjs/index.d.cts +6 -6
  14. package/dist/cjs/indexes.cjs +52 -16
  15. package/dist/cjs/indexes.cjs.map +1 -1
  16. package/dist/cjs/indexes.d.cts +42 -9
  17. package/dist/cjs/multiset.d.cts +8 -2
  18. package/dist/cjs/operators/concat.d.cts +2 -2
  19. package/dist/cjs/operators/consolidate.d.cts +2 -2
  20. package/dist/cjs/operators/distinct.d.cts +2 -2
  21. package/dist/cjs/operators/filter.d.cts +3 -3
  22. package/dist/cjs/operators/groupBy.cjs +33 -36
  23. package/dist/cjs/operators/groupBy.cjs.map +1 -1
  24. package/dist/cjs/operators/groupBy.d.cts +6 -7
  25. package/dist/cjs/operators/groupedOrderBy.d.cts +8 -2
  26. package/dist/cjs/operators/groupedTopKWithFractionalIndex.cjs +3 -9
  27. package/dist/cjs/operators/groupedTopKWithFractionalIndex.cjs.map +1 -1
  28. package/dist/cjs/operators/groupedTopKWithFractionalIndex.d.cts +24 -11
  29. package/dist/cjs/operators/index.d.cts +15 -21
  30. package/dist/cjs/operators/join.cjs +0 -20
  31. package/dist/cjs/operators/join.cjs.map +1 -1
  32. package/dist/cjs/operators/join.d.cts +29 -30
  33. package/dist/cjs/operators/map.d.cts +3 -3
  34. package/dist/cjs/operators/orderBy.cjs +2 -77
  35. package/dist/cjs/operators/orderBy.cjs.map +1 -1
  36. package/dist/cjs/operators/orderBy.d.cts +10 -24
  37. package/dist/cjs/operators/output.d.cts +3 -3
  38. package/dist/cjs/operators/pipe.d.cts +1 -1
  39. package/dist/cjs/operators/reduce.cjs +36 -5
  40. package/dist/cjs/operators/reduce.cjs.map +1 -1
  41. package/dist/cjs/operators/reduce.d.cts +38 -5
  42. package/dist/cjs/operators/tap.d.cts +3 -3
  43. package/dist/cjs/operators/topKArray.cjs +9 -0
  44. package/dist/cjs/operators/topKArray.cjs.map +1 -1
  45. package/dist/cjs/operators/topKArray.d.cts +17 -2
  46. package/dist/cjs/operators/topKState.cjs +3 -0
  47. package/dist/cjs/operators/topKState.cjs.map +1 -1
  48. package/dist/cjs/operators/topKState.d.cts +45 -8
  49. package/dist/cjs/operators/topKWithFractionalIndex.cjs +5 -9
  50. package/dist/cjs/operators/topKWithFractionalIndex.cjs.map +1 -1
  51. package/dist/cjs/operators/topKWithFractionalIndex.d.cts +37 -9
  52. package/dist/cjs/types.d.cts +6 -3
  53. package/dist/cjs/utils.cjs.map +1 -1
  54. package/dist/cjs/utils.d.cts +4 -8
  55. package/dist/esm/hashing/hash.d.ts +9 -0
  56. package/dist/esm/hashing/hash.js +60 -5
  57. package/dist/esm/hashing/hash.js.map +1 -1
  58. package/dist/esm/hashing/murmur.d.ts +2 -0
  59. package/dist/esm/hashing/murmur.js +26 -15
  60. package/dist/esm/hashing/murmur.js.map +1 -1
  61. package/dist/esm/index.js +11 -37
  62. package/dist/esm/index.js.map +1 -1
  63. package/dist/esm/indexes.d.ts +4 -1
  64. package/dist/esm/indexes.js +52 -16
  65. package/dist/esm/indexes.js.map +1 -1
  66. package/dist/esm/operators/groupBy.d.ts +1 -5
  67. package/dist/esm/operators/groupBy.js +33 -36
  68. package/dist/esm/operators/groupBy.js.map +1 -1
  69. package/dist/esm/operators/groupedTopKWithFractionalIndex.d.ts +1 -6
  70. package/dist/esm/operators/groupedTopKWithFractionalIndex.js +3 -9
  71. package/dist/esm/operators/groupedTopKWithFractionalIndex.js.map +1 -1
  72. package/dist/esm/operators/index.d.ts +0 -6
  73. package/dist/esm/operators/join.d.ts +1 -26
  74. package/dist/esm/operators/join.js +1 -21
  75. package/dist/esm/operators/join.js.map +1 -1
  76. package/dist/esm/operators/orderBy.d.ts +2 -22
  77. package/dist/esm/operators/orderBy.js +3 -78
  78. package/dist/esm/operators/orderBy.js.map +1 -1
  79. package/dist/esm/operators/reduce.d.ts +11 -2
  80. package/dist/esm/operators/reduce.js +36 -5
  81. package/dist/esm/operators/reduce.js.map +1 -1
  82. package/dist/esm/operators/topKArray.d.ts +6 -0
  83. package/dist/esm/operators/topKArray.js +10 -1
  84. package/dist/esm/operators/topKArray.js.map +1 -1
  85. package/dist/esm/operators/topKState.d.ts +1 -0
  86. package/dist/esm/operators/topKState.js +3 -0
  87. package/dist/esm/operators/topKState.js.map +1 -1
  88. package/dist/esm/operators/topKWithFractionalIndex.d.ts +7 -3
  89. package/dist/esm/operators/topKWithFractionalIndex.js +6 -10
  90. package/dist/esm/operators/topKWithFractionalIndex.js.map +1 -1
  91. package/dist/esm/utils.d.ts +0 -7
  92. package/dist/esm/utils.js.map +1 -1
  93. package/package.json +3 -5
  94. package/src/hashing/hash.ts +87 -5
  95. package/src/hashing/murmur.ts +31 -17
  96. package/src/indexes.ts +65 -16
  97. package/src/operators/groupBy.ts +48 -59
  98. package/src/operators/groupedTopKWithFractionalIndex.ts +4 -15
  99. package/src/operators/index.ts +0 -6
  100. package/src/operators/join.ts +1 -91
  101. package/src/operators/orderBy.ts +6 -141
  102. package/src/operators/reduce.ts +62 -5
  103. package/src/operators/topKArray.ts +15 -0
  104. package/src/operators/topKState.ts +7 -0
  105. package/src/operators/topKWithFractionalIndex.ts +15 -16
  106. package/src/utils.ts +0 -30
  107. package/dist/cjs/operators/count.cjs +0 -35
  108. package/dist/cjs/operators/count.cjs.map +0 -1
  109. package/dist/cjs/operators/count.d.cts +0 -13
  110. package/dist/cjs/operators/debug.cjs +0 -39
  111. package/dist/cjs/operators/debug.cjs.map +0 -1
  112. package/dist/cjs/operators/debug.d.cts +0 -16
  113. package/dist/cjs/operators/filterBy.cjs +0 -19
  114. package/dist/cjs/operators/filterBy.cjs.map +0 -1
  115. package/dist/cjs/operators/filterBy.d.cts +0 -9
  116. package/dist/cjs/operators/keying.cjs +0 -16
  117. package/dist/cjs/operators/keying.cjs.map +0 -1
  118. package/dist/cjs/operators/keying.d.cts +0 -19
  119. package/dist/cjs/operators/negate.cjs +0 -27
  120. package/dist/cjs/operators/negate.cjs.map +0 -1
  121. package/dist/cjs/operators/negate.d.cts +0 -13
  122. package/dist/cjs/operators/topK.cjs +0 -39
  123. package/dist/cjs/operators/topK.cjs.map +0 -1
  124. package/dist/cjs/operators/topK.d.cts +0 -31
  125. package/dist/cjs/operators/topKWithFractionalIndexBTree.d.cts +0 -28
  126. package/dist/esm/operators/count.d.ts +0 -13
  127. package/dist/esm/operators/count.js +0 -35
  128. package/dist/esm/operators/count.js.map +0 -1
  129. package/dist/esm/operators/debug.d.ts +0 -16
  130. package/dist/esm/operators/debug.js +0 -39
  131. package/dist/esm/operators/debug.js.map +0 -1
  132. package/dist/esm/operators/filterBy.d.ts +0 -9
  133. package/dist/esm/operators/filterBy.js +0 -19
  134. package/dist/esm/operators/filterBy.js.map +0 -1
  135. package/dist/esm/operators/keying.d.ts +0 -19
  136. package/dist/esm/operators/keying.js +0 -16
  137. package/dist/esm/operators/keying.js.map +0 -1
  138. package/dist/esm/operators/negate.d.ts +0 -13
  139. package/dist/esm/operators/negate.js +0 -27
  140. package/dist/esm/operators/negate.js.map +0 -1
  141. package/dist/esm/operators/topK.d.ts +0 -31
  142. package/dist/esm/operators/topK.js +0 -39
  143. package/dist/esm/operators/topK.js.map +0 -1
  144. package/dist/esm/operators/topKWithFractionalIndexBTree.d.ts +0 -28
  145. package/src/operators/count.ts +0 -51
  146. package/src/operators/debug.ts +0 -57
  147. package/src/operators/filterBy.ts +0 -30
  148. package/src/operators/keying.ts +0 -34
  149. package/src/operators/negate.ts +0 -32
  150. package/src/operators/topK.ts +0 -91
  151. package/src/operators/topKWithFractionalIndexBTree.ts +0 -297
@@ -1 +1 @@
1
- {"version":3,"file":"topKArray.cjs","sources":["../../../src/operators/topKArray.ts"],"sourcesContent":["import { generateKeyBetween } from 'fractional-indexing'\nimport { binarySearch, compareKeys, diffHalfOpen } from '../utils.js'\nimport type { HRange } from '../utils.js'\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 */\nexport function 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\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 */\nexport class 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 if (this.#topKStart === this.#topKEnd) return result\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 if (this.#topKStart === this.#topKEnd) return result\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"],"names":["compareKeys","diffHalfOpen","generateKeyBetween","binarySearch"],"mappings":";;;;AAQO,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;AAMO,SAAS,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KAAK,cAAc,OAAO,OAAO,CAAC;AAExD,QAAI,KAAK,eAAe,KAAK,SAAU,QAAO;AAG9C,QAAI,QAAQ,KAAK,UAAU;AAIzB,aAAO,UAAU;AACjB,UAAI,QAAQ,KAAK,YAAY;AAM3B,cAAM,eAAe,KAAK,aAAa;AACvC,YAAI,eAAe,KAAK,cAAc,QAAQ;AAC5C,iBAAO,UAAU,KAAK,cAAc,YAAY;AAAA,QAClD,OAAO;AAGL,iBAAO,UAAU;AAAA,QACnB;AAAA,MACF;AAKA,YAAM,cAAc,KAAK,WAAW;AACpC,UAAI,cAAc,KAAK,cAAc,QAAQ;AAC3C,eAAO,SAAS,KAAK,cAAc,WAAW;AAAA,MAChD;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAMA,WAAW,OAAkB;AAC3B,WAAOC,MAAAA;AAAAA,MAAa,KAAK;AAAA,MAAe,aAAa,OAAO,EAAE;AAAA,MAAG,CAAC,GAAG,MACnE,KAAK,YAAY,SAAS,CAAC,GAAG,SAAS,CAAC,CAAC;AAAA,IAAA;AAAA,EAE7C;AACF;;;;;;"}
1
+ {"version":3,"file":"topKArray.cjs","sources":["../../../src/operators/topKArray.ts"],"sourcesContent":["import { generateKeyBetween } from 'fractional-indexing'\nimport { binarySearch, compareKeys, diffHalfOpen } from '../utils.js'\nimport type { HRange } from '../utils.js'\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 */\nexport function 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\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 /**\n * The number of leading window values that satisfy a predicate that holds\n * for a prefix of the window order. Optional; a caller falls back to size.\n */\n countLeadingInWindow?: (predicate: (value: V) => boolean) => 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 */\nexport class 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 countLeadingInWindow(predicate: (value: V) => boolean): number {\n let count = 0\n const end = this.#topKStart + this.size\n for (let index = this.#topKStart; index < end; index++) {\n if (!predicate(getValue(this.#sortedValues[index]!))) break\n count++\n }\n return count\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 if (this.#topKStart === this.#topKEnd) return result\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 if (this.#topKStart === this.#topKEnd) return result\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"],"names":["compareKeys","diffHalfOpen","generateKeyBetween","binarySearch"],"mappings":";;;;AAQO,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;AAMO,SAAS,sBACd,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,WAAOA,MAAAA,YAAY,MAAM,IAAI;AAAA,EAC/B;AACF;AAuCO,MAAM,UAAgC;AAAA,EAC3C,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,KAA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AAU,KAAK,cAAc,YAAY;AAAA,QAClD,OAAO;AAGL,iBAAO,UAAU;AAAA,QACnB;AAAA,MACF;AAKA,YAAM,cAAc,KAAK,WAAW;AACpC,UAAI,cAAc,KAAK,cAAc,QAAQ;AAC3C,eAAO,SAAS,KAAK,cAAc,WAAW;AAAA,MAChD;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAMA,WAAW,OAAkB;AAC3B,WAAOC,MAAAA;AAAAA,MAAa,KAAK;AAAA,MAAe,aAAa,OAAO,EAAE;AAAA,MAAG,CAAC,GAAG,MACnE,KAAK,YAAY,SAAS,CAAC,GAAG,SAAS,CAAC,CAAC;AAAA,IAAA;AAAA,EAE7C;AACF;;;;;;"}
@@ -1,5 +1,8 @@
1
1
  export type FractionalIndex = string;
2
- export type IndexedValue<V> = [V, FractionalIndex];
2
+ export type IndexedValue<V> = [
3
+ V,
4
+ FractionalIndex
5
+ ];
3
6
  export declare function indexedValue<V>(value: V, index: FractionalIndex): IndexedValue<V>;
4
7
  export declare function getValue<V>(indexedVal: IndexedValue<V>): V;
5
8
  export declare function getIndex<V>(indexedVal: IndexedValue<V>): FractionalIndex;
@@ -7,7 +10,13 @@ export declare function getIndex<V>(indexedVal: IndexedValue<V>): FractionalInde
7
10
  * Creates a comparator for [key, value] tuples that first compares values,
8
11
  * then uses the row key as a stable tie-breaker.
9
12
  */
10
- export declare function createKeyedComparator<K extends string | number, T>(comparator: (a: T, b: T) => number): (a: [K, T], b: [K, T]) => number;
13
+ export declare function createKeyedComparator<K extends string | number, T>(comparator: (a: T, b: T) => number): (a: [
14
+ K,
15
+ T
16
+ ], b: [
17
+ K,
18
+ T
19
+ ]) => number;
11
20
  export type TopKChanges<V> = {
12
21
  /** Indicates which element moves into the topK (if any) */
13
22
  moveIn: IndexedValue<V> | null;
@@ -28,6 +37,11 @@ export type TopKMoveChanges<V> = {
28
37
  */
29
38
  export interface TopK<V> {
30
39
  size: number;
40
+ /**
41
+ * The number of leading window values that satisfy a predicate that holds
42
+ * for a prefix of the window order. Optional; a caller falls back to size.
43
+ */
44
+ countLeadingInWindow?: (predicate: (value: V) => boolean) => number;
31
45
  insert: (value: V) => TopKChanges<V>;
32
46
  delete: (value: V) => TopKChanges<V>;
33
47
  }
@@ -41,6 +55,7 @@ export declare class TopKArray<V> implements TopK<V> {
41
55
  #private;
42
56
  constructor(offset: number, limit: number, comparator: (a: V, b: V) => number);
43
57
  get size(): number;
58
+ countLeadingInWindow(predicate: (value: V) => boolean): number;
44
59
  /**
45
60
  * Moves the topK window
46
61
  */
@@ -39,6 +39,9 @@ class TopKState {
39
39
  get size() {
40
40
  return this.#topK.size;
41
41
  }
42
+ countLeadingInWindow(predicate) {
43
+ return this.#topK.countLeadingInWindow?.(([, value]) => predicate(value)) ?? this.#topK.size;
44
+ }
42
45
  get isEmpty() {
43
46
  return this.#multiplicities.size === 0 && this.#topK.size === 0;
44
47
  }
@@ -1 +1 @@
1
- {"version":3,"file":"topKState.cjs","sources":["../../../src/operators/topKState.ts"],"sourcesContent":["import { equalHashValues } from '../hashing/hash.js'\nimport { TopKArray } from './topKArray.js'\nimport type { MultiSet } from '../multiset.js'\nimport type {\n IndexedValue,\n TopK,\n TopKChanges,\n TopKMoveChanges,\n} from './topKArray.js'\n\n/** Apply a keyed batch's retractions before additions. An outer join can emit\n * a replacement in the opposite order; key multiplicity alone would hide it.\n * Consolidate first so a transient value added and removed in this same turn\n * cannot be mistaken for the final replacement. Use structural relation\n * identity: map can allocate a fresh value for each side of a cancelling pair.\n * No state survives the run.\n */\nexport function* topKBatch<K, T>(messages: Array<MultiSet<[K, T]>>) {\n const keyed = new Map<K, Array<[[K, T], number]>>()\n for (const message of messages) {\n for (const [value, weight] of message.getInner()) {\n const entries = keyed.get(value[0])\n if (entries) entries.push([value, weight])\n else keyed.set(value[0], [[value, weight]])\n }\n }\n const batch: Array<[[K, T], number]> = []\n for (const entries of keyed.values()) {\n // Ordering distinct keys needs only the caller's comparator. In particular,\n // do not traverse irrelevant payloads or merge keys on a hash collision.\n if (entries.length === 1) {\n batch.push(entries[0]!)\n continue\n }\n // A per-key scan keeps normal two-version replacements cheap and permits\n // cycles, at the cost of quadratic comparisons for long same-key histories.\n const consolidated: Array<[[K, T], number]> = []\n for (const [value, weight] of entries) {\n const previous = consolidated.find(([candidate]) =>\n equalHashValues(candidate[1], value[1]),\n )\n if (previous) previous[1] += weight\n else consolidated.push([value, weight])\n }\n batch.push(...consolidated)\n }\n for (const entry of batch) if (entry[1] < 0) yield entry\n for (const entry of batch) if (entry[1] > 0) yield entry\n}\n\n/**\n * Helper class that manages the state for a single topK window.\n * Encapsulates the multiplicity tracking and topK data structure,\n * providing a clean interface for processing elements and moving the window.\n *\n * This class is used by both TopKWithFractionalIndexOperator (single instance)\n * and GroupedTopKWithFractionalIndexOperator (one instance per group).\n */\nexport class TopKState<K extends string | number, T> {\n #multiplicities: Map<K, number> = new Map()\n #topK: TopK<[K, T]>\n\n constructor(topK: TopK<[K, T]>) {\n this.#topK = topK\n }\n\n get size(): number {\n return this.#topK.size\n }\n\n get isEmpty(): boolean {\n return this.#multiplicities.size === 0 && this.#topK.size === 0\n }\n\n /**\n * Process an element update (insert or delete based on multiplicity change).\n * Returns the changes to the topK window.\n */\n processElement(key: K, value: T, multiplicity: number): TopKChanges<[K, T]> {\n const { oldMultiplicity, newMultiplicity } = this.#updateMultiplicity(\n key,\n multiplicity,\n )\n\n if (oldMultiplicity <= 0 && newMultiplicity > 0) {\n // The value was invisible but should now be visible\n return this.#topK.insert([key, value])\n } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {\n // The value was visible but should now be invisible\n return this.#topK.delete([key, value])\n }\n // The value was invisible and remains invisible,\n // or was visible and remains visible - no topK change\n return { moveIn: null, moveOut: null }\n }\n\n /**\n * Move the topK window. Only works with TopKArray implementation.\n */\n move(options: { offset?: number; limit?: number }): TopKMoveChanges<[K, T]> {\n if (!(this.#topK instanceof TopKArray)) {\n throw new Error(\n `Cannot move B+-tree implementation of TopK with fractional index`,\n )\n }\n return this.#topK.move(options)\n }\n\n #updateMultiplicity(\n key: K,\n multiplicity: number,\n ): { oldMultiplicity: number; newMultiplicity: number } {\n if (multiplicity === 0) {\n const current = this.#multiplicities.get(key) ?? 0\n return { oldMultiplicity: current, newMultiplicity: current }\n }\n\n const oldMultiplicity = this.#multiplicities.get(key) ?? 0\n const newMultiplicity = oldMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.#multiplicities.delete(key)\n } else {\n this.#multiplicities.set(key, newMultiplicity)\n }\n return { oldMultiplicity, newMultiplicity }\n }\n}\n\n/**\n * Handles a moveIn change by adding it to the result array.\n */\nexport function handleMoveIn<K extends string | number, T>(\n moveIn: IndexedValue<[K, T]> | null,\n result: Array<[[K, IndexedValue<T>], number]>,\n): void {\n if (moveIn) {\n const [[key, value], index] = moveIn\n result.push([[key, [value, index]], 1])\n }\n}\n\n/**\n * Handles a moveOut change by adding it to the result array.\n */\nexport function handleMoveOut<K extends string | number, T>(\n moveOut: IndexedValue<[K, T]> | null,\n result: Array<[[K, IndexedValue<T>], number]>,\n): void {\n if (moveOut) {\n const [[key, value], index] = moveOut\n result.push([[key, [value, index]], -1])\n }\n}\n"],"names":["equalHashValues","TopKArray"],"mappings":";;;;AAiBO,UAAU,UAAgB,UAAmC;AAClE,QAAM,4BAAY,IAAA;AAClB,aAAW,WAAW,UAAU;AAC9B,eAAW,CAAC,OAAO,MAAM,KAAK,QAAQ,YAAY;AAChD,YAAM,UAAU,MAAM,IAAI,MAAM,CAAC,CAAC;AAClC,UAAI,QAAS,SAAQ,KAAK,CAAC,OAAO,MAAM,CAAC;AAAA,UACpC,OAAM,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC;AAAA,IAC5C;AAAA,EACF;AACA,QAAM,QAAiC,CAAA;AACvC,aAAW,WAAW,MAAM,UAAU;AAGpC,QAAI,QAAQ,WAAW,GAAG;AACxB,YAAM,KAAK,QAAQ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KAAK,iBAAiBC,UAAAA,YAAY;AACtC,YAAM,IAAI;AAAA,QACR;AAAA,MAAA;AAAA,IAEJ;AACA,WAAO,KAAK,MAAM,KAAK,OAAO;AAAA,EAChC;AAAA,EAEA,oBACE,KACA,cACsD;AACtD,QAAI,iBAAiB,GAAG;AACtB,YAAM,UAAU,KAAK,gBAAgB,IAAI,GAAG,KAAK;AACjD,aAAO,EAAE,iBAAiB,SAAS,iBAAiB,QAAA;AAAA,IACtD;AAEA,UAAM,kBAAkB,KAAK,gBAAgB,IAAI,GAAG,KAAK;AACzD,UAAM,kBAAkB,kBAAkB;AAC1C,QAAI,oBAAoB,GAAG;AACzB,WAAK,gBAAgB,OAAO,GAAG;AAAA,IACjC,OAAO;AACL,WAAK,gBAAgB,IAAI,KAAK,eAAe;AAAA,IAC/C;AACA,WAAO,EAAE,iBAAiB,gBAAA;AAAA,EAC5B;AACF;AAKO,SAAS,aACd,QACA,QACM;AACN,MAAI,QAAQ;AACV,UAAM,CAAC,CAAC,KAAK,KAAK,GAAG,KAAK,IAAI;AAC9B,WAAO,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC;AAAA,EACxC;AACF;AAKO,SAAS,cACd,SACA,QACM;AACN,MAAI,SAAS;AACX,UAAM,CAAC,CAAC,KAAK,KAAK,GAAG,KAAK,IAAI;AAC9B,WAAO,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,KAAK,CAAC,GAAG,EAAE,CAAC;AAAA,EACzC;AACF;;;;;"}
1
+ {"version":3,"file":"topKState.cjs","sources":["../../../src/operators/topKState.ts"],"sourcesContent":["import { equalHashValues } from '../hashing/hash.js'\nimport { TopKArray } from './topKArray.js'\nimport type { MultiSet } from '../multiset.js'\nimport type {\n IndexedValue,\n TopK,\n TopKChanges,\n TopKMoveChanges,\n} from './topKArray.js'\n\n/** Apply a keyed batch's retractions before additions. An outer join can emit\n * a replacement in the opposite order; key multiplicity alone would hide it.\n * Consolidate first so a transient value added and removed in this same turn\n * cannot be mistaken for the final replacement. Use structural relation\n * identity: map can allocate a fresh value for each side of a cancelling pair.\n * No state survives the run.\n */\nexport function* topKBatch<K, T>(messages: Array<MultiSet<[K, T]>>) {\n const keyed = new Map<K, Array<[[K, T], number]>>()\n for (const message of messages) {\n for (const [value, weight] of message.getInner()) {\n const entries = keyed.get(value[0])\n if (entries) entries.push([value, weight])\n else keyed.set(value[0], [[value, weight]])\n }\n }\n const batch: Array<[[K, T], number]> = []\n for (const entries of keyed.values()) {\n // Ordering distinct keys needs only the caller's comparator. In particular,\n // do not traverse irrelevant payloads or merge keys on a hash collision.\n if (entries.length === 1) {\n batch.push(entries[0]!)\n continue\n }\n // A per-key scan keeps normal two-version replacements cheap and permits\n // cycles, at the cost of quadratic comparisons for long same-key histories.\n const consolidated: Array<[[K, T], number]> = []\n for (const [value, weight] of entries) {\n const previous = consolidated.find(([candidate]) =>\n equalHashValues(candidate[1], value[1]),\n )\n if (previous) previous[1] += weight\n else consolidated.push([value, weight])\n }\n batch.push(...consolidated)\n }\n for (const entry of batch) if (entry[1] < 0) yield entry\n for (const entry of batch) if (entry[1] > 0) yield entry\n}\n\n/**\n * Helper class that manages the state for a single topK window.\n * Encapsulates the multiplicity tracking and topK data structure,\n * providing a clean interface for processing elements and moving the window.\n *\n * This class is used by both TopKWithFractionalIndexOperator (single instance)\n * and GroupedTopKWithFractionalIndexOperator (one instance per group).\n */\nexport class TopKState<K extends string | number, T> {\n #multiplicities: Map<K, number> = new Map()\n #topK: TopK<[K, T]>\n\n constructor(topK: TopK<[K, T]>) {\n this.#topK = topK\n }\n\n get size(): number {\n return this.#topK.size\n }\n\n countLeadingInWindow(predicate: (value: T) => boolean): number {\n return (\n this.#topK.countLeadingInWindow?.(([, value]) => predicate(value)) ??\n this.#topK.size\n )\n }\n\n get isEmpty(): boolean {\n return this.#multiplicities.size === 0 && this.#topK.size === 0\n }\n\n /**\n * Process an element update (insert or delete based on multiplicity change).\n * Returns the changes to the topK window.\n */\n processElement(key: K, value: T, multiplicity: number): TopKChanges<[K, T]> {\n const { oldMultiplicity, newMultiplicity } = this.#updateMultiplicity(\n key,\n multiplicity,\n )\n\n if (oldMultiplicity <= 0 && newMultiplicity > 0) {\n // The value was invisible but should now be visible\n return this.#topK.insert([key, value])\n } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {\n // The value was visible but should now be invisible\n return this.#topK.delete([key, value])\n }\n // The value was invisible and remains invisible,\n // or was visible and remains visible - no topK change\n return { moveIn: null, moveOut: null }\n }\n\n /**\n * Move the topK window. Only works with TopKArray implementation.\n */\n move(options: { offset?: number; limit?: number }): TopKMoveChanges<[K, T]> {\n if (!(this.#topK instanceof TopKArray)) {\n throw new Error(\n `Cannot move B+-tree implementation of TopK with fractional index`,\n )\n }\n return this.#topK.move(options)\n }\n\n #updateMultiplicity(\n key: K,\n multiplicity: number,\n ): { oldMultiplicity: number; newMultiplicity: number } {\n if (multiplicity === 0) {\n const current = this.#multiplicities.get(key) ?? 0\n return { oldMultiplicity: current, newMultiplicity: current }\n }\n\n const oldMultiplicity = this.#multiplicities.get(key) ?? 0\n const newMultiplicity = oldMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.#multiplicities.delete(key)\n } else {\n this.#multiplicities.set(key, newMultiplicity)\n }\n return { oldMultiplicity, newMultiplicity }\n }\n}\n\n/**\n * Handles a moveIn change by adding it to the result array.\n */\nexport function handleMoveIn<K extends string | number, T>(\n moveIn: IndexedValue<[K, T]> | null,\n result: Array<[[K, IndexedValue<T>], number]>,\n): void {\n if (moveIn) {\n const [[key, value], index] = moveIn\n result.push([[key, [value, index]], 1])\n }\n}\n\n/**\n * Handles a moveOut change by adding it to the result array.\n */\nexport function handleMoveOut<K extends string | number, T>(\n moveOut: IndexedValue<[K, T]> | null,\n result: Array<[[K, IndexedValue<T>], number]>,\n): void {\n if (moveOut) {\n const [[key, value], index] = moveOut\n result.push([[key, [value, index]], -1])\n }\n}\n"],"names":["equalHashValues","TopKArray"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G,KAAK,IAAI;AAC9B,WAAO,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC;AAAA,EACxC;AACF;AAKO,SAAS,cACd,SACA,QACM;AACN,MAAI,SAAS;AACX,UAAM,CAAC,CAAC,KAAK,KAAK,GAAG,KAAK,IAAI;AAC9B,WAAO,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,KAAK,CAAC,GAAG,EAAE,CAAC;AAAA,EACzC;AACF;;;;;"}
@@ -1,5 +1,5 @@
1
- import { MultiSet } from '../multiset.js';
2
- import { IndexedValue, TopK, TopKChanges, TopKMoveChanges } from './topKArray.js';
1
+ import { MultiSet } from "../multiset.cjs";
2
+ import { IndexedValue, TopK, TopKChanges, TopKMoveChanges } from "./topKArray.cjs";
3
3
  /** Apply a keyed batch's retractions before additions. An outer join can emit
4
4
  * a replacement in the opposite order; key multiplicity alone would hide it.
5
5
  * Consolidate first so a transient value added and removed in this same turn
@@ -7,7 +7,16 @@ import { IndexedValue, TopK, TopKChanges, TopKMoveChanges } from './topKArray.js
7
7
  * identity: map can allocate a fresh value for each side of a cancelling pair.
8
8
  * No state survives the run.
9
9
  */
10
- export declare function topKBatch<K, T>(messages: Array<MultiSet<[K, T]>>): Generator<[[K, T], number], void, unknown>;
10
+ export declare function topKBatch<K, T>(messages: Array<MultiSet<[
11
+ K,
12
+ T
13
+ ]>>): Generator<[
14
+ [
15
+ K,
16
+ T
17
+ ],
18
+ number
19
+ ], void, unknown>;
11
20
  /**
12
21
  * Helper class that manages the state for a single topK window.
13
22
  * Encapsulates the multiplicity tracking and topK data structure,
@@ -18,27 +27,55 @@ export declare function topKBatch<K, T>(messages: Array<MultiSet<[K, T]>>): Gene
18
27
  */
19
28
  export declare class TopKState<K extends string | number, T> {
20
29
  #private;
21
- constructor(topK: TopK<[K, T]>);
30
+ constructor(topK: TopK<[
31
+ K,
32
+ T
33
+ ]>);
22
34
  get size(): number;
35
+ countLeadingInWindow(predicate: (value: T) => boolean): number;
23
36
  get isEmpty(): boolean;
24
37
  /**
25
38
  * Process an element update (insert or delete based on multiplicity change).
26
39
  * Returns the changes to the topK window.
27
40
  */
28
- processElement(key: K, value: T, multiplicity: number): TopKChanges<[K, T]>;
41
+ processElement(key: K, value: T, multiplicity: number): TopKChanges<[
42
+ K,
43
+ T
44
+ ]>;
29
45
  /**
30
46
  * Move the topK window. Only works with TopKArray implementation.
31
47
  */
32
48
  move(options: {
33
49
  offset?: number;
34
50
  limit?: number;
35
- }): TopKMoveChanges<[K, T]>;
51
+ }): TopKMoveChanges<[
52
+ K,
53
+ T
54
+ ]>;
36
55
  }
37
56
  /**
38
57
  * Handles a moveIn change by adding it to the result array.
39
58
  */
40
- export declare function handleMoveIn<K extends string | number, T>(moveIn: IndexedValue<[K, T]> | null, result: Array<[[K, IndexedValue<T>], number]>): void;
59
+ export declare function handleMoveIn<K extends string | number, T>(moveIn: IndexedValue<[
60
+ K,
61
+ T
62
+ ]> | null, result: Array<[
63
+ [
64
+ K,
65
+ IndexedValue<T>
66
+ ],
67
+ number
68
+ ]>): void;
41
69
  /**
42
70
  * Handles a moveOut change by adding it to the result array.
43
71
  */
44
- export declare function handleMoveOut<K extends string | number, T>(moveOut: IndexedValue<[K, T]> | null, result: Array<[[K, IndexedValue<T>], number]>): void;
72
+ export declare function handleMoveOut<K extends string | number, T>(moveOut: IndexedValue<[
73
+ K,
74
+ T
75
+ ]> | null, result: Array<[
76
+ [
77
+ K,
78
+ IndexedValue<T>
79
+ ],
80
+ number
81
+ ]>): void;
@@ -11,18 +11,14 @@ class TopKWithFractionalIndexOperator extends graph.UnaryOperator {
11
11
  super(id, inputA, output);
12
12
  const limit = options.limit ?? Infinity;
13
13
  const offset = options.offset ?? 0;
14
- const topK = this.createTopK(
15
- offset,
16
- limit,
17
- topKArray.createKeyedComparator(comparator)
14
+ this.#state = new topKState.TopKState(
15
+ new topKArray.TopKArray(offset, limit, topKArray.createKeyedComparator(comparator))
16
+ );
17
+ options.setSizeCallback?.(
18
+ (counts) => counts ? this.#state.countLeadingInWindow(counts) : this.#state.size
18
19
  );
19
- this.#state = new topKState.TopKState(topK);
20
- options.setSizeCallback?.(() => this.#state.size);
21
20
  options.setWindowFn?.(this.moveTopK.bind(this));
22
21
  }
23
- createTopK(offset, limit, comparator) {
24
- return new topKArray.TopKArray(offset, limit, comparator);
25
- }
26
22
  /**
27
23
  * Moves the topK window based on the provided offset and limit.
28
24
  * Any changes to the topK are sent to the output.
@@ -1 +1 @@
1
- {"version":3,"file":"topKWithFractionalIndex.cjs","sources":["../../../src/operators/topKWithFractionalIndex.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport { MultiSet } from '../multiset.js'\nimport {\n TopKState,\n handleMoveIn,\n handleMoveOut,\n topKBatch,\n} from './topKState.js'\nimport { TopKArray, createKeyedComparator } from './topKArray.js'\nimport type { IndexedValue, TopK } from './topKArray.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\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 #state: TopKState<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 topK = this.createTopK(\n offset,\n limit,\n createKeyedComparator(comparator),\n )\n this.#state = new TopKState(topK)\n options.setSizeCallback?.(() => this.#state.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 const result: Array<[[K, IndexedValue<T>], number]> = []\n const diff = this.#state.move({ offset, limit })\n\n diff.moveIns.forEach((moveIn) => handleMoveIn(moveIn, result))\n diff.moveOuts.forEach((moveOut) => 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 [[key, value], multiplicity] of topKBatch(\n this.inputMessages(),\n )) {\n this.processElement(key, value, multiplicity, result)\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 changes = this.#state.processElement(key, value, multiplicity)\n handleMoveIn(changes.moveIn, result)\n handleMoveOut(changes.moveOut, result)\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"],"names":["UnaryOperator","createKeyedComparator","TopKState","TopKArray","handleMoveIn","handleMoveOut","MultiSet","topKBatch","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;;;;AA4BO,MAAM,wCAGHA,MAAAA,cAA4C;AAAA,EACpD;AAAA,EAEA,YACE,IACA,QACA,QACA,YACA,SACA;AACA,UAAM,IAAI,QAAQ,MAAM;AACxB,UAAM,QAAQ,QAAQ,SAAS;AAC/B,UAAM,SAAS,QAAQ,UAAU;AACjC,UAAM,OAAO,KAAK;AAAA,MAChB;AAAA,MACA;AAAA,MACAC,UAAAA,sBAAsB,UAAU;AAAA,IAAA;AAElC,SAAK,SAAS,IAAIC,UAAAA,UAAU,IAAI;AAChC,YAAQ,kBAAkB,MAAM,KAAK,OAAO,IAAI;AAChD,YAAQ,cAAc,KAAK,SAAS,KAAK,IAAI,CAAC;AAAA,EAChD;AAAA,EAEU,WACR,QACA,OACA,YACc;AACd,WAAO,IAAIC,UAAAA,UAAU,QAAQ,OAAO,UAAU;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAS,EAAE,QAAQ,SAA8C;AAC/D,UAAM,SAAgD,CAAA;AACtD,UAAM,OAAO,KAAK,OAAO,KAAK,EAAE,QAAQ,OAAO;AAE/C,SAAK,QAAQ,QAAQ,CAAC,WAAWC,uBAAa,QAAQ,MAAM,CAAC;AAC7D,SAAK,SAAS,QAAQ,CAAC,YAAYC,wBAAc,SAAS,MAAM,CAAC;AAEjE,QAAI,KAAK,SAAS;AAIhB,WAAK,OAAO,SAAS,IAAIC,SAAAA,SAAS,MAAM,CAAC;AAAA,IAC3C;AAAA,EACF;AAAA,EAEA,MAAY;AACV,UAAM,SAAgD,CAAA;AACtD,eAAW,CAAC,CAAC,KAAK,KAAK,GAAG,YAAY,KAAKC,UAAAA;AAAAA,MACzC,KAAK,cAAA;AAAA,IAAc,GAClB;AACD,WAAK,eAAe,KAAK,OAAO,cAAc,MAAM;AAAA,IACtD;AAEA,QAAI,OAAO,SAAS,GAAG;AACrB,WAAK,OAAO,SAAS,IAAID,SAAAA,SAAS,MAAM,CAAC;AAAA,IAC3C;AAAA,EACF;AAAA,EAEA,eACE,KACA,OACA,cACA,QACM;AACN,UAAM,UAAU,KAAK,OAAO,eAAe,KAAK,OAAO,YAAY;AACnEF,2BAAa,QAAQ,QAAQ,MAAM;AACnCC,4BAAc,QAAQ,SAAS,MAAM;AAAA,EACvC;AACF;AAYO,SAAS,wBACd,YACA,SACqD;AACrD,QAAM,OAAO,WAAW,CAAA;AAExB,SAAO,CACL,WAC6C;AAC7C,UAAM,SAAS,IAAIG,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;;;"}
1
+ {"version":3,"file":"topKWithFractionalIndex.cjs","sources":["../../../src/operators/topKWithFractionalIndex.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport { MultiSet } from '../multiset.js'\nimport {\n TopKState,\n handleMoveIn,\n handleMoveOut,\n topKBatch,\n} from './topKState.js'\nimport { TopKArray, createKeyedComparator } from './topKArray.js'\nimport type { IndexedValue } from './topKArray.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?: SetSizeCallback\n setWindowFn?: (\n windowFn: (options: { offset?: number; limit?: number }) => void,\n ) => void\n}\n\n/**\n * Receives the window size. Given a predicate that holds for a prefix of the\n * window order, the getter counts only the leading values that satisfy it.\n */\nexport type SetSizeCallback = (\n getSize: (counts?: (value: unknown) => boolean) => number,\n) => void\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 #state: TopKState<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.#state = new TopKState(\n new TopKArray(offset, limit, createKeyedComparator(comparator)),\n )\n options.setSizeCallback?.((counts) =>\n counts ? this.#state.countLeadingInWindow(counts) : this.#state.size,\n )\n options.setWindowFn?.(this.moveTopK.bind(this))\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 const result: Array<[[K, IndexedValue<T>], number]> = []\n const diff = this.#state.move({ offset, limit })\n\n diff.moveIns.forEach((moveIn) => handleMoveIn(moveIn, result))\n diff.moveOuts.forEach((moveOut) => 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 [[key, value], multiplicity] of topKBatch(\n this.inputMessages(),\n )) {\n this.processElement(key, value, multiplicity, result)\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 changes = this.#state.processElement(key, value, multiplicity)\n handleMoveIn(changes.moveIn, result)\n handleMoveOut(changes.moveOut, result)\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"],"names":["UnaryOperator","TopKState","TopKArray","createKeyedComparator","handleMoveIn","handleMoveOut","MultiSet","topKBatch","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;;;;AAoCO,MAAM,wCAGHA,MAAAA,cAA4C;AAAA,EACpD;AAAA,EAEA,YACE,IACA,QACA,QACA,YACA,SACA;AACA,UAAM,IAAI,QAAQ,MAAM;AACxB,UAAM,QAAQ,QAAQ,SAAS;AAC/B,UAAM,SAAS,QAAQ,UAAU;AACjC,SAAK,SAAS,IAAIC,UAAAA;AAAAA,MAChB,IAAIC,UAAAA,UAAU,QAAQ,OAAOC,UAAAA,sBAA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A,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;;;"}
@@ -1,24 +1,40 @@
1
- import { DifferenceStreamWriter, UnaryOperator, DifferenceStreamReader } from '../graph.js';
2
- import { IndexedValue, TopK } from './topKArray.js';
3
- import { PipedOperator } from '../types.js';
1
+ import { DifferenceStreamWriter, UnaryOperator, DifferenceStreamReader } from "../graph.cjs";
2
+ import { IndexedValue } from "./topKArray.cjs";
3
+ import { PipedOperator } from "../types.cjs";
4
4
  export interface TopKWithFractionalIndexOptions {
5
5
  limit?: number;
6
6
  offset?: number;
7
- setSizeCallback?: (getSize: () => number) => void;
7
+ setSizeCallback?: SetSizeCallback;
8
8
  setWindowFn?: (windowFn: (options: {
9
9
  offset?: number;
10
10
  limit?: number;
11
11
  }) => void) => void;
12
12
  }
13
+ /**
14
+ * Receives the window size. Given a predicate that holds for a prefix of the
15
+ * window order, the getter counts only the leading values that satisfy it.
16
+ */
17
+ export type SetSizeCallback = (getSize: (counts?: (value: unknown) => boolean) => number) => void;
13
18
  /**
14
19
  * Operator for fractional indexed topK operations
15
20
  * This operator maintains fractional indices for sorted elements
16
21
  * and only updates indices when elements move position
17
22
  */
18
- export declare class TopKWithFractionalIndexOperator<K extends string | number, T> extends UnaryOperator<[K, T], [K, IndexedValue<T>]> {
23
+ export declare class TopKWithFractionalIndexOperator<K extends string | number, T> extends UnaryOperator<[
24
+ K,
25
+ T
26
+ ], [
27
+ K,
28
+ IndexedValue<T>
29
+ ]> {
19
30
  #private;
20
- constructor(id: number, inputA: DifferenceStreamReader<[K, T]>, output: DifferenceStreamWriter<[K, IndexedValue<T>]>, comparator: (a: T, b: T) => number, options: TopKWithFractionalIndexOptions);
21
- protected createTopK(offset: number, limit: number, comparator: (a: [K, T], b: [K, T]) => number): TopK<[K, T]>;
31
+ constructor(id: number, inputA: DifferenceStreamReader<[
32
+ K,
33
+ T
34
+ ]>, output: DifferenceStreamWriter<[
35
+ K,
36
+ IndexedValue<T>
37
+ ]>, comparator: (a: T, b: T) => number, options: TopKWithFractionalIndexOptions);
22
38
  /**
23
39
  * Moves the topK window based on the provided offset and limit.
24
40
  * Any changes to the topK are sent to the output.
@@ -28,7 +44,13 @@ export declare class TopKWithFractionalIndexOperator<K extends string | number,
28
44
  limit?: number;
29
45
  }): void;
30
46
  run(): void;
31
- processElement(key: K, value: T, multiplicity: number, result: Array<[[K, IndexedValue<T>], number]>): void;
47
+ processElement(key: K, value: T, multiplicity: number, result: Array<[
48
+ [
49
+ K,
50
+ IndexedValue<T>
51
+ ],
52
+ number
53
+ ]>): void;
32
54
  }
33
55
  /**
34
56
  * Limits the number of results based on a comparator, with optional offset.
@@ -40,4 +62,10 @@ export declare class TopKWithFractionalIndexOperator<K extends string | number,
40
62
  * @param options - An optional object containing limit and offset properties
41
63
  * @returns A piped operator that orders the elements and limits the number of results
42
64
  */
43
- export declare function topKWithFractionalIndex<KType extends string | number, T>(comparator: (a: T, b: T) => number, options?: TopKWithFractionalIndexOptions): PipedOperator<[KType, T], [KType, IndexedValue<T>]>;
65
+ export declare function topKWithFractionalIndex<KType extends string | number, T>(comparator: (a: T, b: T) => number, options?: TopKWithFractionalIndexOptions): PipedOperator<[
66
+ KType,
67
+ T
68
+ ], [
69
+ KType,
70
+ IndexedValue<T>
71
+ ]>;
@@ -1,6 +1,9 @@
1
- import { MultiSet, MultiSetArray } from './multiset.js';
2
- import { BinaryOperator, DifferenceStreamReader, DifferenceStreamWriter, UnaryOperator } from './graph.js';
3
- export type KeyValue<K, V> = [K, V];
1
+ import { MultiSet, MultiSetArray } from "./multiset.cjs";
2
+ import { BinaryOperator, DifferenceStreamReader, DifferenceStreamWriter, UnaryOperator } from "./graph.cjs";
3
+ export type KeyValue<K, V> = [
4
+ K,
5
+ V
6
+ ];
4
7
  export interface IOperator<_T> {
5
8
  run: () => void;
6
9
  hasPendingWork: () => boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["import { isTemporal } from './hashing/temporal.js'\n\n/**\n * Simple assertion function for runtime checks.\n * Throws an error if the condition is false.\n */\nexport function assert(\n condition: unknown,\n message?: string,\n): asserts condition {\n if (!condition) {\n throw new Error(message || `Assertion failed`)\n }\n}\n\n// JS engines have various limits on how many args can be passed to a function\n// with a spread operator, so we need to split the operation into chunks\n// 32767 is the max for Chrome 14, all others are higher\n// TODO: investigate the performance of this and other approaches\nconst chunkSize = 30000\nexport function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>) {\n if (other.length <= chunkSize) {\n array.push(...other)\n } else {\n for (let i = 0; i < other.length; i += chunkSize) {\n const chunk = other.slice(i, i + chunkSize)\n array.push(...chunk)\n }\n }\n}\n\nexport function binarySearch<T>(\n array: Array<T>,\n value: T,\n comparator: (a: T, b: T) => number,\n): number {\n let low = 0\n let high = array.length\n while (low < high) {\n const mid = Math.floor((low + high) / 2)\n const comparison = comparator(array[mid]!, value)\n if (comparison < 0) {\n low = mid + 1\n } else if (comparison > 0) {\n high = mid\n } else {\n return mid\n }\n }\n return low\n}\n\n/**\n * A string identity within one consolidation: primitives by value, objects,\n * functions, and symbols by identity.\n */\nexport function getStringId(\n value: unknown,\n referenceIds: Map<object | symbol, number>,\n): string {\n if (value === null) return `null`\n if (value === undefined) return `undefined`\n const type = typeof value\n if (type === `object` || type === `function` || type === `symbol`) {\n const reference = value as object | symbol\n let id = referenceIds.get(reference)\n if (id === undefined) referenceIds.set(reference, (id = referenceIds.size))\n return `ref_${id}`\n }\n return `${type}_${String(value)}`\n}\n\nexport function* concatIterable<T>(\n ...iterables: Array<Iterable<T>>\n): Iterable<T> {\n for (const iterable of iterables) {\n yield* iterable\n }\n}\n\nexport function* mapIterable<T, U>(\n it: Iterable<T>,\n fn: (t: T) => U,\n): Iterable<U> {\n for (const t of it) {\n yield fn(t)\n }\n}\n\nexport type HRange = [number, number] // half-open [start, end[ i.e. end is exclusive\n\n/**\n * Computes the difference between two half-open ranges.\n * @param a - The first half-open range\n * @param b - The second half-open range\n * @returns The difference between the two ranges\n */\nexport function diffHalfOpen(a: HRange, b: HRange) {\n const [a1, a2] = a\n const [b1, b2] = b\n\n // A \\ B can be up to two segments (left and right of the overlap)\n const onlyInA: Array<number> = [\n ...range(a1, Math.min(a2, b1)), // left side of A outside B\n ...range(Math.max(a1, b2), a2), // right side of A outside B\n ]\n\n // B \\ A similarly\n const onlyInB: Array<number> = [\n ...range(b1, Math.min(b2, a1)),\n ...range(Math.max(b1, a2), b2),\n ]\n\n return { onlyInA, onlyInB }\n}\n\nfunction range(start: number, end: number): Array<number> {\n const out: Array<number> = []\n for (let i = start; i < end; i++) out.push(i)\n return out\n}\n\n/**\n * Compares two keys (string | number) in a consistent, deterministic way.\n * Handles mixed types by ordering strings before numbers.\n */\nexport function compareKeys(a: string | number, b: string | number): number {\n // Same type: compare directly\n if (typeof a === typeof b) {\n if (typeof a === `number` && typeof b === `number`) {\n const aIsNaN = Number.isNaN(a)\n const bIsNaN = Number.isNaN(b)\n if (aIsNaN || bIsNaN) {\n if (aIsNaN && bIsNaN) return 0\n return aIsNaN ? 1 : -1\n }\n }\n if (a < b) return -1\n if (a > b) return 1\n return 0\n }\n // Different types: strings come before numbers\n return typeof a === `string` ? -1 : 1\n}\n\ntype CanonicalValue =\n | readonly [`undefined`]\n | readonly [`null`]\n | readonly [`boolean`, boolean]\n | readonly [`number`, number | `NaN` | `Infinity` | `-Infinity`]\n | readonly [`bigint`, string]\n | readonly [`string`, string]\n | readonly [`date`, number | `Invalid`]\n | readonly [`temporal`, string, string]\n | readonly [`regexp`, string, string]\n | readonly [`bytes`, Array<number>]\n | readonly [`array`, Array<CanonicalValue>]\n | readonly [`map`, Array<readonly [CanonicalValue, CanonicalValue]>]\n | readonly [`set`, Array<CanonicalValue>]\n | readonly [`object`, Array<readonly [string, CanonicalValue]>]\n\n/**\n * Serializes a supported query value into one canonical key.\n *\n * JSON's native encoding is not suitable for relation keys: it merges BigInt\n * with strings when a replacer is used, merges NaN with null, drops undefined,\n * and depends on object insertion order. Ordinary JSON values keep their\n * established wire form. Values that need richer types use a reserved prefix\n * plus a structural, type-tagged encoding.\n */\nexport function serializeValue(value: unknown): string {\n if (isJsonSafeStructuralValue(value, new Set())) {\n return JSON.stringify(toStableJsonValue(value))\n }\n\n return `~${JSON.stringify(toCanonicalValue(value, new Set()))}`\n}\n\ntype JsonValue =\n | null\n | boolean\n | number\n | string\n | Array<JsonValue>\n | { [key: string]: JsonValue }\n\nfunction isJsonSafeStructuralValue(\n value: unknown,\n ancestors: Set<object>,\n): boolean {\n if (value === null) return true\n\n switch (typeof value) {\n case `boolean`:\n case `string`:\n return true\n case `number`:\n return Number.isFinite(value)\n case `undefined`:\n case `bigint`:\n case `symbol`:\n case `function`:\n return false\n }\n\n return withAcyclicValue(value, ancestors, () => {\n if (\n value instanceof Date ||\n value instanceof RegExp ||\n value instanceof Uint8Array ||\n isTemporal(value) ||\n value instanceof Map ||\n value instanceof Set\n ) {\n return false\n }\n\n return Array.isArray(value)\n ? value.every((item) => isJsonSafeStructuralValue(item, ancestors))\n : Object.keys(value).every((key) =>\n isJsonSafeStructuralValue(\n (value as Record<string, unknown>)[key],\n ancestors,\n ),\n )\n })\n}\n\nfunction toStableJsonValue(value: unknown): JsonValue {\n if (\n value === null ||\n typeof value === `boolean` ||\n typeof value === `number` ||\n typeof value === `string`\n ) {\n return value\n }\n\n if (Array.isArray(value)) {\n return value.map(toStableJsonValue)\n }\n\n return Object.fromEntries(\n Object.keys(value as object)\n .sort()\n .map((key) => [\n key,\n toStableJsonValue((value as Record<string, unknown>)[key]),\n ]),\n )\n}\n\nfunction toCanonicalValue(\n value: unknown,\n ancestors: Set<object>,\n): CanonicalValue {\n if (value === undefined) return [`undefined`]\n if (value === null) return [`null`]\n\n switch (typeof value) {\n case `boolean`:\n return [`boolean`, value]\n case `number`:\n if (Number.isNaN(value)) return [`number`, `NaN`]\n if (value === Infinity) return [`number`, `Infinity`]\n if (value === -Infinity) return [`number`, `-Infinity`]\n return [`number`, value === 0 ? 0 : value]\n case `bigint`:\n return [`bigint`, value.toString()]\n case `string`:\n return [`string`, value]\n case `symbol`:\n case `function`:\n throw new TypeError(\n `Cannot serialize ${typeof value} as a structural relation key`,\n )\n }\n\n return withAcyclicValue(value, ancestors, () => {\n if (value instanceof Date) {\n const timestamp = value.getTime()\n return Number.isNaN(timestamp)\n ? ([`date`, `Invalid`] as const)\n : ([`date`, timestamp] as const)\n }\n\n if (value instanceof RegExp) {\n return [`regexp`, value.source, value.flags]\n }\n\n if (value instanceof Uint8Array) {\n return [`bytes`, Array.from(value)]\n }\n\n if (isTemporal(value)) {\n return [`temporal`, value[Symbol.toStringTag], value.toString()]\n }\n\n if (Array.isArray(value)) {\n return [`array`, value.map((item) => toCanonicalValue(item, ancestors))]\n }\n\n if (value instanceof Map) {\n const entries = [...value.entries()].map(\n ([key, entryValue]) =>\n [\n toCanonicalValue(key, ancestors),\n toCanonicalValue(entryValue, ancestors),\n ] as const,\n )\n entries.sort((left, right) =>\n compareSerializedValues(JSON.stringify(left), JSON.stringify(right)),\n )\n return [`map`, entries]\n }\n\n if (value instanceof Set) {\n const entries = [...value].map((entry) =>\n toCanonicalValue(entry, ancestors),\n )\n entries.sort((left, right) =>\n compareSerializedValues(JSON.stringify(left), JSON.stringify(right)),\n )\n return [`set`, entries]\n }\n\n const entries = Object.keys(value)\n .sort()\n .map(\n (key) =>\n [\n key,\n toCanonicalValue(\n (value as Record<string, unknown>)[key],\n ancestors,\n ),\n ] as const,\n )\n return [`object`, entries]\n })\n}\n\nfunction compareSerializedValues(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction withAcyclicValue<T>(\n value: object,\n ancestors: Set<object>,\n encode: () => T,\n): T {\n if (ancestors.has(value)) {\n throw new TypeError(`Cannot serialize a cyclic structural relation key`)\n }\n\n ancestors.add(value)\n try {\n return encode()\n } finally {\n ancestors.delete(value)\n }\n}\n"],"names":["isTemporal","entries"],"mappings":";;;AAmBA,MAAM,YAAY;AACX,SAAS,iBAAiB,OAAuB,OAAuB;AAC7E,MAAI,MAAM,UAAU,WAAW;AAC7B,UAAM,KAAK,GAAG,KAAK;AAAA,EACrB,OAAO;AACL,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;AAChD,YAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,SAAS;AAC1C,YAAM,KAAK,GAAG,KAAK;AAAA,IACrB;AAAA,EACF;AACF;AAEO,SAAS,aACd,OACA,OACA,YACQ;AACR,MAAI,MAAM;AACV,MAAI,OAAO,MAAM;AACjB,SAAO,MAAM,MAAM;AACjB,UAAM,MAAM,KAAK,OAAO,MAAM,QAAQ,CAAC;AACvC,UAAM,aAAa,WAAW,MAAM,GAAG,GAAI,KAAK;AAChD,QAAI,aAAa,GAAG;AAClB,YAAM,MAAM;AAAA,IACd,WAAW,aAAa,GAAG;AACzB,aAAO;AAAA,IACT,OAAO;AACL,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAMO,SAAS,YACd,OACA,cACQ;AACR,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,UAAU,OAAW,QAAO;AAChC,QAAM,OAAO,OAAO;AACpB,MAAI,SAAS,YAAY,SAAS,cAAc,SAAS,UAAU;AACjE,UAAM,YAAY;AAClB,QAAI,KAAK,aAAa,IAAI,SAAS;AACnC,QAAI,OAAO,OAAW,cAAa,IAAI,WAAY,KAAK,aAAa,IAAK;AAC1E,WAAO,OAAO,EAAE;AAAA,EAClB;AACA,SAAO,GAAG,IAAI,IAAI,OAAO,KAAK,CAAC;AACjC;AA2BO,SAAS,aAAa,GAAW,GAAW;AACjD,QAAM,CAAC,IAAI,EAAE,IAAI;AACjB,QAAM,CAAC,IAAI,EAAE,IAAI;AA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K,CAAC;AAAA,MAAA;AAErE,aAAO,CAAC,OAAOA,QAAO;AAAA,IACxB;AAEA,QAAI,iBAAiB,KAAK;AACxB,YAAMA,WAAU,CAAC,GAAG,KAAK,EAAE;AAAA,QAAI,CAAC,UAC9B,iBAAiB,OAAO,SAAS;AAAA,MAAA;AAEnCA,eAAQ;AAAA,QAAK,CAAC,MAAM,UAClB,wBAAwB,KAAK,UAAU,IAAI,GAAG,KAAK,UAAU,KAAK,CAAC;AAAA,MAAA;AAErE,aAAO,CAAC,OAAOA,QAAO;AAAA,IACxB;AAEA,UAAM,UAAU,OAAO,KAAK,KAAK,EAC9B,OACA;AAAA,MACC,CAAC,QACC;AAAA,QACE;AAAA,QACA;AAAA,UACG,MAAkC,GAAG;AAAA,UACtC;AAAA,QAAA;AAAA,MACF;AAAA,IACF;AAEN,WAAO,CAAC,UAAU,OAAO;AAAA,EAC3B,CAAC;AACH;AAEA,SAAS,wBAAwB,MAAc,OAAuB;AACpE,SAAO,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChD;AAEA,SAAS,iBACP,OACA,WACA,QACG;AACH,MAAI,UAAU,IAAI,KAAK,GAAG;AACxB,UAAM,IAAI,UAAU,mDAAmD;AAAA,EACzE;AAEA,YAAU,IAAI,KAAK;AACnB,MAAI;AACF,WAAO,OAAA;AAAA,EACT,UAAA;AACE,cAAU,OAAO,KAAK;AAAA,EACxB;AACF;;;;;;;"}
1
+ {"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["import { isTemporal } from './hashing/temporal.js'\n\n// JS engines have various limits on how many args can be passed to a function\n// with a spread operator, so we need to split the operation into chunks\n// 32767 is the max for Chrome 14, all others are higher\n// TODO: investigate the performance of this and other approaches\nconst chunkSize = 30000\nexport function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>) {\n if (other.length <= chunkSize) {\n array.push(...other)\n } else {\n for (let i = 0; i < other.length; i += chunkSize) {\n const chunk = other.slice(i, i + chunkSize)\n array.push(...chunk)\n }\n }\n}\n\nexport function binarySearch<T>(\n array: Array<T>,\n value: T,\n comparator: (a: T, b: T) => number,\n): number {\n let low = 0\n let high = array.length\n while (low < high) {\n const mid = Math.floor((low + high) / 2)\n const comparison = comparator(array[mid]!, value)\n if (comparison < 0) {\n low = mid + 1\n } else if (comparison > 0) {\n high = mid\n } else {\n return mid\n }\n }\n return low\n}\n\n/**\n * A string identity within one consolidation: primitives by value, objects,\n * functions, and symbols by identity.\n */\nexport function getStringId(\n value: unknown,\n referenceIds: Map<object | symbol, number>,\n): string {\n if (value === null) return `null`\n if (value === undefined) return `undefined`\n const type = typeof value\n if (type === `object` || type === `function` || type === `symbol`) {\n const reference = value as object | symbol\n let id = referenceIds.get(reference)\n if (id === undefined) referenceIds.set(reference, (id = referenceIds.size))\n return `ref_${id}`\n }\n return `${type}_${String(value)}`\n}\n\nexport type HRange = [number, number] // half-open [start, end[ i.e. end is exclusive\n\n/**\n * Computes the difference between two half-open ranges.\n * @param a - The first half-open range\n * @param b - The second half-open range\n * @returns The difference between the two ranges\n */\nexport function diffHalfOpen(a: HRange, b: HRange) {\n const [a1, a2] = a\n const [b1, b2] = b\n\n // A \\ B can be up to two segments (left and right of the overlap)\n const onlyInA: Array<number> = [\n ...range(a1, Math.min(a2, b1)), // left side of A outside B\n ...range(Math.max(a1, b2), a2), // right side of A outside B\n ]\n\n // B \\ A similarly\n const onlyInB: Array<number> = [\n ...range(b1, Math.min(b2, a1)),\n ...range(Math.max(b1, a2), b2),\n ]\n\n return { onlyInA, onlyInB }\n}\n\nfunction range(start: number, end: number): Array<number> {\n const out: Array<number> = []\n for (let i = start; i < end; i++) out.push(i)\n return out\n}\n\n/**\n * Compares two keys (string | number) in a consistent, deterministic way.\n * Handles mixed types by ordering strings before numbers.\n */\nexport function compareKeys(a: string | number, b: string | number): number {\n // Same type: compare directly\n if (typeof a === typeof b) {\n if (typeof a === `number` && typeof b === `number`) {\n const aIsNaN = Number.isNaN(a)\n const bIsNaN = Number.isNaN(b)\n if (aIsNaN || bIsNaN) {\n if (aIsNaN && bIsNaN) return 0\n return aIsNaN ? 1 : -1\n }\n }\n if (a < b) return -1\n if (a > b) return 1\n return 0\n }\n // Different types: strings come before numbers\n return typeof a === `string` ? -1 : 1\n}\n\ntype CanonicalValue =\n | readonly [`undefined`]\n | readonly [`null`]\n | readonly [`boolean`, boolean]\n | readonly [`number`, number | `NaN` | `Infinity` | `-Infinity`]\n | readonly [`bigint`, string]\n | readonly [`string`, string]\n | readonly [`date`, number | `Invalid`]\n | readonly [`temporal`, string, string]\n | readonly [`regexp`, string, string]\n | readonly [`bytes`, Array<number>]\n | readonly [`array`, Array<CanonicalValue>]\n | readonly [`map`, Array<readonly [CanonicalValue, CanonicalValue]>]\n | readonly [`set`, Array<CanonicalValue>]\n | readonly [`object`, Array<readonly [string, CanonicalValue]>]\n\n/**\n * Serializes a supported query value into one canonical key.\n *\n * JSON's native encoding is not suitable for relation keys: it merges BigInt\n * with strings when a replacer is used, merges NaN with null, drops undefined,\n * and depends on object insertion order. Ordinary JSON values keep their\n * established wire form. Values that need richer types use a reserved prefix\n * plus a structural, type-tagged encoding.\n */\nexport function serializeValue(value: unknown): string {\n if (isJsonSafeStructuralValue(value, new Set())) {\n return JSON.stringify(toStableJsonValue(value))\n }\n\n return `~${JSON.stringify(toCanonicalValue(value, new Set()))}`\n}\n\ntype JsonValue =\n | null\n | boolean\n | number\n | string\n | Array<JsonValue>\n | { [key: string]: JsonValue }\n\nfunction isJsonSafeStructuralValue(\n value: unknown,\n ancestors: Set<object>,\n): boolean {\n if (value === null) return true\n\n switch (typeof value) {\n case `boolean`:\n case `string`:\n return true\n case `number`:\n return Number.isFinite(value)\n case `undefined`:\n case `bigint`:\n case `symbol`:\n case `function`:\n return false\n }\n\n return withAcyclicValue(value, ancestors, () => {\n if (\n value instanceof Date ||\n value instanceof RegExp ||\n value instanceof Uint8Array ||\n isTemporal(value) ||\n value instanceof Map ||\n value instanceof Set\n ) {\n return false\n }\n\n return Array.isArray(value)\n ? value.every((item) => isJsonSafeStructuralValue(item, ancestors))\n : Object.keys(value).every((key) =>\n isJsonSafeStructuralValue(\n (value as Record<string, unknown>)[key],\n ancestors,\n ),\n )\n })\n}\n\nfunction toStableJsonValue(value: unknown): JsonValue {\n if (\n value === null ||\n typeof value === `boolean` ||\n typeof value === `number` ||\n typeof value === `string`\n ) {\n return value\n }\n\n if (Array.isArray(value)) {\n return value.map(toStableJsonValue)\n }\n\n return Object.fromEntries(\n Object.keys(value as object)\n .sort()\n .map((key) => [\n key,\n toStableJsonValue((value as Record<string, unknown>)[key]),\n ]),\n )\n}\n\nfunction toCanonicalValue(\n value: unknown,\n ancestors: Set<object>,\n): CanonicalValue {\n if (value === undefined) return [`undefined`]\n if (value === null) return [`null`]\n\n switch (typeof value) {\n case `boolean`:\n return [`boolean`, value]\n case `number`:\n if (Number.isNaN(value)) return [`number`, `NaN`]\n if (value === Infinity) return [`number`, `Infinity`]\n if (value === -Infinity) return [`number`, `-Infinity`]\n return [`number`, value === 0 ? 0 : value]\n case `bigint`:\n return [`bigint`, value.toString()]\n case `string`:\n return [`string`, value]\n case `symbol`:\n case `function`:\n throw new TypeError(\n `Cannot serialize ${typeof value} as a structural relation key`,\n )\n }\n\n return withAcyclicValue(value, ancestors, () => {\n if (value instanceof Date) {\n const timestamp = value.getTime()\n return Number.isNaN(timestamp)\n ? ([`date`, `Invalid`] as const)\n : ([`date`, timestamp] as const)\n }\n\n if (value instanceof RegExp) {\n return [`regexp`, value.source, value.flags]\n }\n\n if (value instanceof Uint8Array) {\n return [`bytes`, Array.from(value)]\n }\n\n if (isTemporal(value)) {\n return [`temporal`, value[Symbol.toStringTag], value.toString()]\n }\n\n if (Array.isArray(value)) {\n return [`array`, value.map((item) => toCanonicalValue(item, ancestors))]\n }\n\n if (value instanceof Map) {\n const entries = [...value.entries()].map(\n ([key, entryValue]) =>\n [\n toCanonicalValue(key, ancestors),\n toCanonicalValue(entryValue, ancestors),\n ] as const,\n )\n entries.sort((left, right) =>\n compareSerializedValues(JSON.stringify(left), JSON.stringify(right)),\n )\n return [`map`, entries]\n }\n\n if (value instanceof Set) {\n const entries = [...value].map((entry) =>\n toCanonicalValue(entry, ancestors),\n )\n entries.sort((left, right) =>\n compareSerializedValues(JSON.stringify(left), JSON.stringify(right)),\n )\n return [`set`, entries]\n }\n\n const entries = Object.keys(value)\n .sort()\n .map(\n (key) =>\n [\n key,\n toCanonicalValue(\n (value as Record<string, unknown>)[key],\n ancestors,\n ),\n ] as const,\n )\n return [`object`, entries]\n })\n}\n\nfunction compareSerializedValues(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction withAcyclicValue<T>(\n value: object,\n ancestors: Set<object>,\n encode: () => T,\n): T {\n if (ancestors.has(value)) {\n throw new TypeError(`Cannot serialize a cyclic structural relation key`)\n }\n\n ancestors.add(value)\n try {\n return encode()\n } finally {\n ancestors.delete(value)\n }\n}\n"],"names":["isTemporal","entries"],"mappings":";;;AAMA,MAAM,YAAY;AACX,SAAS,iBAAiB,OAAuB,OAAuB;AAC7E,MAAI,MAAM,UAAU,WAAW;AAC7B,UAAM,KAAK,GAAG,KAAK;AAAA,EACrB,OAAO;AACL,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;AAChD,YAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,SAAS;AAC1C,YAAM,KAAK,GAAG,KAAK;AAAA,IACrB;AAAA,EACF;AACF;AAEO,SAAS,aACd,OACA,OACA,YACQ;AACR,MAAI,MAAM;AACV,MAAI,OAAO,MAAM;AACjB,SAAO,MAAM,MAAM;AACjB,UAAM,MAAM,KAAK,OAAO,MAAM,QAAQ,CAAC;AACvC,UAAM,aAAa,WAAW,MAAM,GAAG,GAAI,KAAK;AAChD,QAAI,aAAa,GAAG;AAClB,YAAM,MAAM;AAAA,IACd,WAAW,aAAa,GAAG;AACzB,aAAO;AAAA,IACT,OAAO;AACL,aAAO;AAAA,IACT;AAAA,EACF;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DAAmD;AAAA,EACzE;AAEA,YAAU,IAAI,KAAK;AACnB,MAAI;AACF,WAAO,OAAA;AAAA,EACT,UAAA;AACE,cAAU,OAAO,KAAK;AAAA,EACxB;AACF;;;;;;;"}
@@ -1,8 +1,3 @@
1
- /**
2
- * Simple assertion function for runtime checks.
3
- * Throws an error if the condition is false.
4
- */
5
- export declare function assert(condition: unknown, message?: string): asserts condition;
6
1
  export declare function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>): void;
7
2
  export declare function binarySearch<T>(array: Array<T>, value: T, comparator: (a: T, b: T) => number): number;
8
3
  /**
@@ -10,9 +5,10 @@ export declare function binarySearch<T>(array: Array<T>, value: T, comparator: (
10
5
  * functions, and symbols by identity.
11
6
  */
12
7
  export declare function getStringId(value: unknown, referenceIds: Map<object | symbol, number>): string;
13
- export declare function concatIterable<T>(...iterables: Array<Iterable<T>>): Iterable<T>;
14
- export declare function mapIterable<T, U>(it: Iterable<T>, fn: (t: T) => U): Iterable<U>;
15
- export type HRange = [number, number];
8
+ export type HRange = [
9
+ number,
10
+ number
11
+ ];
16
12
  /**
17
13
  * Computes the difference between two half-open ranges.
18
14
  * @param a - The first half-open range
@@ -6,3 +6,12 @@ export declare function hash(input: any): number;
6
6
  * Reference-valued leaves remain opaque, including registered mutable handles.
7
7
  */
8
8
  export declare function equalHashValues(left: unknown, right: unknown): boolean;
9
+ /**
10
+ * @internal An exact identity string for a value, or undefined when it has
11
+ * no cheap one. Two values that `equalHashValues` treats as equal get the
12
+ * same result, both undefined or one string; two that it treats as different
13
+ * never share a string. The decision uses only what equalHashValues reads:
14
+ * the type, the `objectParts` marker and headers, and enumerable own keys. groupBy uses it
15
+ * to merge equal contributions without hashing them.
16
+ */
17
+ export declare function structuralIdentity(value: unknown, depth?: number): string | undefined;
@@ -1,4 +1,4 @@
1
- import { MurmurHashStream, randomHash, getSymbolIdentity } from "./murmur.js";
1
+ import { MurmurHashStream, getSymbolIdentity, randomHash } from "./murmur.js";
2
2
  import { isTemporal } from "./temporal.js";
3
3
  const TRUE = randomHash();
4
4
  const FALSE = randomHash();
@@ -43,7 +43,9 @@ function hashObject(input, context) {
43
43
  if (body) updateHasher(hasher, value, context);
44
44
  else hasher.update(value);
45
45
  if (body) {
46
- const keys = Object.keys(body).sort(keySort);
46
+ const keys = Object.keys(body);
47
+ const denseArray = Array.isArray(body) && keys.length === body.length && (keys.length === 0 || keys[keys.length - 1] === String(body.length - 1));
48
+ if (!denseArray) keys.sort();
47
49
  keys.push(
48
50
  ...Object.getOwnPropertySymbols(body).filter(
49
51
  (key) => Object.prototype.propertyIsEnumerable.call(body, key)
@@ -177,12 +179,65 @@ function cachedReferenceHash(fn) {
177
179
  }
178
180
  return valueHash;
179
181
  }
180
- function keySort(a, b) {
181
- return a.localeCompare(b);
182
+ const MARKER_TAGS = /* @__PURE__ */ new Map([
183
+ [ARRAY_MARKER, `[`],
184
+ [OBJECT_MARKER, `{`],
185
+ [DATE_MARKER, `<`],
186
+ [REGEXP_MARKER, `/`],
187
+ [MAP_MARKER, `&`],
188
+ [SET_MARKER, `*`],
189
+ [UINT8ARRAY_MARKER, `^`],
190
+ [TEMPORAL_MARKER, `?`]
191
+ ]);
192
+ const MAX_IDENTITY_DEPTH = 4;
193
+ function structuralIdentity(value, depth = 0) {
194
+ switch (typeof value) {
195
+ case `number`:
196
+ return `#${value === 0 ? 0 : value}`;
197
+ case `string`:
198
+ return `"${value.length}:${value}`;
199
+ case `boolean`:
200
+ return value ? `+` : `-`;
201
+ case `undefined`:
202
+ return `~`;
203
+ case `bigint`:
204
+ return `%${value}`;
205
+ case `symbol`:
206
+ return `$${getSymbolIdentity(value)}`;
207
+ case `object`: {
208
+ if (value === null) return `!`;
209
+ if (depth >= MAX_IDENTITY_DEPTH || isReferenceHashedObject(value))
210
+ return void 0;
211
+ const [marker, header, body] = objectParts(value);
212
+ let head = MARKER_TAGS.get(marker);
213
+ for (const part of header) {
214
+ if (Number.isNaN(part)) return void 0;
215
+ head += structuralIdentity(part, depth + 1);
216
+ }
217
+ if (!body) return head;
218
+ if (Object.getOwnPropertySymbols(body).some(
219
+ (key) => Object.prototype.propertyIsEnumerable.call(body, key)
220
+ ))
221
+ return void 0;
222
+ let parts = ``;
223
+ for (const key of Object.keys(body).sort()) {
224
+ const part = structuralIdentity(
225
+ body[key],
226
+ depth + 1
227
+ );
228
+ if (part === void 0) return void 0;
229
+ parts += `${key.length}:${key}=${part}|`;
230
+ }
231
+ return `${head}:${parts.length}:${parts}`;
232
+ }
233
+ default:
234
+ return void 0;
235
+ }
182
236
  }
183
237
  export {
184
238
  equalHashValues,
185
239
  hash,
186
- registerOpaqueHash
240
+ registerOpaqueHash,
241
+ structuralIdentity
187
242
  };
188
243
  //# sourceMappingURL=hash.js.map