@ac-kit/algo 0.5.0 → 0.7.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 (191) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/README.md +60 -18
  3. package/dist/combinatorics/cartesian-product.d.ts +46 -0
  4. package/dist/combinatorics/cartesian-product.d.ts.map +1 -0
  5. package/dist/combinatorics/cartesian-product.js +79 -0
  6. package/dist/combinatorics/cartesian-product.js.map +1 -0
  7. package/dist/combinatorics/permutations.d.ts +41 -0
  8. package/dist/combinatorics/permutations.d.ts.map +1 -0
  9. package/dist/combinatorics/permutations.js +70 -0
  10. package/dist/combinatorics/permutations.js.map +1 -0
  11. package/dist/combinatorics/power-set.d.ts +40 -0
  12. package/dist/combinatorics/power-set.d.ts.map +1 -0
  13. package/dist/combinatorics/power-set.js +67 -0
  14. package/dist/combinatorics/power-set.js.map +1 -0
  15. package/dist/graph/bfs.d.ts +66 -0
  16. package/dist/graph/bfs.d.ts.map +1 -0
  17. package/dist/graph/bfs.js +89 -0
  18. package/dist/graph/bfs.js.map +1 -0
  19. package/dist/graph/connected-components.d.ts +35 -0
  20. package/dist/graph/connected-components.d.ts.map +1 -0
  21. package/dist/graph/connected-components.js +75 -0
  22. package/dist/graph/connected-components.js.map +1 -0
  23. package/dist/graph/find-cycle.d.ts +5 -3
  24. package/dist/graph/find-cycle.d.ts.map +1 -1
  25. package/dist/graph/find-cycle.js +23 -3
  26. package/dist/graph/find-cycle.js.map +1 -1
  27. package/dist/graph/floyd-warshall.d.ts +67 -0
  28. package/dist/graph/floyd-warshall.d.ts.map +1 -0
  29. package/dist/graph/floyd-warshall.js +106 -0
  30. package/dist/graph/floyd-warshall.js.map +1 -0
  31. package/dist/graph/graph-cycle-error.d.ts +16 -0
  32. package/dist/graph/graph-cycle-error.d.ts.map +1 -0
  33. package/dist/graph/graph-cycle-error.js +20 -0
  34. package/dist/graph/graph-cycle-error.js.map +1 -0
  35. package/dist/graph/hierarchy-from-parents.js.map +1 -1
  36. package/dist/graph/lowest-common-ancestor.d.ts +32 -0
  37. package/dist/graph/lowest-common-ancestor.d.ts.map +1 -0
  38. package/dist/graph/lowest-common-ancestor.js +56 -0
  39. package/dist/graph/lowest-common-ancestor.js.map +1 -0
  40. package/dist/graph/topological-sort.d.ts +51 -0
  41. package/dist/graph/topological-sort.d.ts.map +1 -0
  42. package/dist/graph/topological-sort.js +124 -0
  43. package/dist/graph/topological-sort.js.map +1 -0
  44. package/dist/group/_nest-by.d.ts +19 -0
  45. package/dist/group/_nest-by.d.ts.map +1 -0
  46. package/dist/group/_nest-by.js +85 -0
  47. package/dist/group/_nest-by.js.map +1 -0
  48. package/dist/group/count-by.d.ts +31 -0
  49. package/dist/group/count-by.d.ts.map +1 -0
  50. package/dist/group/count-by.js +35 -0
  51. package/dist/group/count-by.js.map +1 -0
  52. package/dist/group/flat-group-by.d.ts +28 -0
  53. package/dist/group/flat-group-by.d.ts.map +1 -0
  54. package/dist/group/flat-group-by.js +30 -0
  55. package/dist/group/flat-group-by.js.map +1 -0
  56. package/dist/group/group-adjacent-by.d.ts +31 -0
  57. package/dist/group/group-adjacent-by.d.ts.map +1 -0
  58. package/dist/group/group-adjacent-by.js +50 -0
  59. package/dist/group/group-adjacent-by.js.map +1 -0
  60. package/dist/group/group-sort.d.ts +38 -0
  61. package/dist/group/group-sort.d.ts.map +1 -0
  62. package/dist/group/group-sort.js +49 -0
  63. package/dist/group/group-sort.js.map +1 -0
  64. package/dist/group/index-by.d.ts +33 -0
  65. package/dist/group/index-by.d.ts.map +1 -0
  66. package/dist/group/index-by.js +42 -0
  67. package/dist/group/index-by.js.map +1 -0
  68. package/dist/group/nested-map.d.ts +12 -0
  69. package/dist/group/nested-map.d.ts.map +1 -0
  70. package/dist/group/nested-map.js +2 -0
  71. package/dist/group/nested-map.js.map +1 -0
  72. package/dist/group/rollup-by.d.ts +62 -0
  73. package/dist/group/rollup-by.d.ts.map +1 -0
  74. package/dist/group/rollup-by.js +72 -0
  75. package/dist/group/rollup-by.js.map +1 -0
  76. package/dist/group/run-length-encode.d.ts +41 -0
  77. package/dist/group/run-length-encode.d.ts.map +1 -0
  78. package/dist/group/run-length-encode.js +66 -0
  79. package/dist/group/run-length-encode.js.map +1 -0
  80. package/dist/index.d.ts +39 -1
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +39 -1
  83. package/dist/index.js.map +1 -1
  84. package/dist/ordered/_fractional-key.d.ts +38 -0
  85. package/dist/ordered/_fractional-key.d.ts.map +1 -0
  86. package/dist/ordered/_fractional-key.js +251 -0
  87. package/dist/ordered/_fractional-key.js.map +1 -0
  88. package/dist/ordered/bisect-right-numbers-array.d.ts +20 -0
  89. package/dist/ordered/bisect-right-numbers-array.d.ts.map +1 -0
  90. package/dist/ordered/bisect-right-numbers-array.js +42 -0
  91. package/dist/ordered/bisect-right-numbers-array.js.map +1 -0
  92. package/dist/ordered/bisect-right-numbers.d.ts +19 -0
  93. package/dist/ordered/bisect-right-numbers.d.ts.map +1 -0
  94. package/dist/ordered/bisect-right-numbers.js +32 -0
  95. package/dist/ordered/bisect-right-numbers.js.map +1 -0
  96. package/dist/ordered/create-bisector.js.map +1 -1
  97. package/dist/ordered/fractional-key-alphabet.d.ts +41 -0
  98. package/dist/ordered/fractional-key-alphabet.d.ts.map +1 -0
  99. package/dist/ordered/fractional-key-alphabet.js +67 -0
  100. package/dist/ordered/fractional-key-alphabet.js.map +1 -0
  101. package/dist/ordered/fractional-key-error.d.ts +15 -0
  102. package/dist/ordered/fractional-key-error.d.ts.map +1 -0
  103. package/dist/ordered/fractional-key-error.js +20 -0
  104. package/dist/ordered/fractional-key-error.js.map +1 -0
  105. package/dist/ordered/fractional-key.d.ts +82 -0
  106. package/dist/ordered/fractional-key.d.ts.map +1 -0
  107. package/dist/ordered/fractional-key.js +199 -0
  108. package/dist/ordered/fractional-key.js.map +1 -0
  109. package/dist/ordered/is-sorted.d.ts +33 -0
  110. package/dist/ordered/is-sorted.d.ts.map +1 -0
  111. package/dist/ordered/is-sorted.js +39 -0
  112. package/dist/ordered/is-sorted.js.map +1 -0
  113. package/dist/sample/sample-without-replacement.d.ts +26 -0
  114. package/dist/sample/sample-without-replacement.d.ts.map +1 -0
  115. package/dist/sample/sample-without-replacement.js +41 -0
  116. package/dist/sample/sample-without-replacement.js.map +1 -0
  117. package/dist/sample/shuffle.d.ts +2 -2
  118. package/dist/sample/shuffle.d.ts.map +1 -1
  119. package/dist/sample/shuffle.js +3 -3
  120. package/dist/sample/shuffle.js.map +1 -1
  121. package/dist/sample/weighted-choice-index.d.ts +29 -0
  122. package/dist/sample/weighted-choice-index.d.ts.map +1 -0
  123. package/dist/sample/weighted-choice-index.js +62 -0
  124. package/dist/sample/weighted-choice-index.js.map +1 -0
  125. package/dist/sample/weighted-choice.d.ts +28 -0
  126. package/dist/sample/weighted-choice.d.ts.map +1 -0
  127. package/dist/sample/weighted-choice.js +31 -0
  128. package/dist/sample/weighted-choice.js.map +1 -0
  129. package/dist/select/minmax.d.ts +52 -0
  130. package/dist/select/minmax.d.ts.map +1 -0
  131. package/dist/select/minmax.js +109 -0
  132. package/dist/select/minmax.js.map +1 -0
  133. package/dist/select/{quickselect.d.ts → quickselect-in-place.d.ts} +2 -2
  134. package/dist/select/quickselect-in-place.d.ts.map +1 -0
  135. package/dist/select/{quickselect.js → quickselect-in-place.js} +3 -3
  136. package/dist/select/quickselect-in-place.js.map +1 -0
  137. package/dist/sequence/_matching-runs.d.ts +16 -0
  138. package/dist/sequence/_matching-runs.d.ts.map +1 -0
  139. package/dist/sequence/_matching-runs.js +178 -0
  140. package/dist/sequence/_matching-runs.js.map +1 -0
  141. package/dist/sequence/common-prefix-length.d.ts +26 -0
  142. package/dist/sequence/common-prefix-length.d.ts.map +1 -0
  143. package/dist/sequence/common-prefix-length.js +34 -0
  144. package/dist/sequence/common-prefix-length.js.map +1 -0
  145. package/dist/sequence/diff-sequences.d.ts +59 -0
  146. package/dist/sequence/diff-sequences.d.ts.map +1 -0
  147. package/dist/sequence/diff-sequences.js +67 -0
  148. package/dist/sequence/diff-sequences.js.map +1 -0
  149. package/dist/sequence/levenshtein-distance.d.ts +43 -0
  150. package/dist/sequence/levenshtein-distance.d.ts.map +1 -0
  151. package/dist/sequence/levenshtein-distance.js +102 -0
  152. package/dist/sequence/levenshtein-distance.js.map +1 -0
  153. package/dist/sequence/longest-common-subsequence.d.ts +28 -0
  154. package/dist/sequence/longest-common-subsequence.d.ts.map +1 -0
  155. package/dist/sequence/longest-common-subsequence.js +39 -0
  156. package/dist/sequence/longest-common-subsequence.js.map +1 -0
  157. package/dist/sequence/longest-increasing-subsequence.d.ts +28 -0
  158. package/dist/sequence/longest-increasing-subsequence.d.ts.map +1 -0
  159. package/dist/sequence/longest-increasing-subsequence.js +47 -0
  160. package/dist/sequence/longest-increasing-subsequence.js.map +1 -0
  161. package/dist/sort/_sort-primitives.d.ts +6 -0
  162. package/dist/sort/_sort-primitives.d.ts.map +1 -0
  163. package/dist/sort/_sort-primitives.js +18 -0
  164. package/dist/sort/_sort-primitives.js.map +1 -0
  165. package/dist/sort/counting-sort.d.ts +40 -0
  166. package/dist/sort/counting-sort.d.ts.map +1 -0
  167. package/dist/sort/counting-sort.js +51 -0
  168. package/dist/sort/counting-sort.js.map +1 -0
  169. package/dist/sort/merge-sort.d.ts +26 -0
  170. package/dist/sort/merge-sort.d.ts.map +1 -0
  171. package/dist/sort/merge-sort.js +73 -0
  172. package/dist/sort/merge-sort.js.map +1 -0
  173. package/dist/sort/quick-sort-in-place.d.ts +35 -0
  174. package/dist/sort/quick-sort-in-place.d.ts.map +1 -0
  175. package/dist/sort/quick-sort-in-place.js +98 -0
  176. package/dist/sort/quick-sort-in-place.js.map +1 -0
  177. package/dist/sort/radix-index-sorter.d.ts +57 -0
  178. package/dist/sort/radix-index-sorter.d.ts.map +1 -0
  179. package/dist/sort/radix-index-sorter.js +204 -0
  180. package/dist/sort/radix-index-sorter.js.map +1 -0
  181. package/dist/sort/rank.d.ts +64 -0
  182. package/dist/sort/rank.d.ts.map +1 -0
  183. package/dist/sort/rank.js +107 -0
  184. package/dist/sort/rank.js.map +1 -0
  185. package/dist/sort/sort-range.d.ts +48 -0
  186. package/dist/sort/sort-range.d.ts.map +1 -0
  187. package/dist/sort/sort-range.js +267 -0
  188. package/dist/sort/sort-range.js.map +1 -0
  189. package/package.json +6 -5
  190. package/dist/select/quickselect.d.ts.map +0 -1
  191. package/dist/select/quickselect.js.map +0 -1
@@ -0,0 +1,82 @@
1
+ import { type FractionalKeyAlphabet } from "./fractional-key-alphabet.js";
2
+ /** Options of the fractional key functions. */
3
+ export type FractionalKeyOptions = {
4
+ /** Default {@link BASE62_FRACTIONAL_KEY_ALPHABET}. */
5
+ readonly alphabet?: FractionalKeyAlphabet;
6
+ };
7
+ /**
8
+ * Whether `key` is a well-formed fractional key under the alphabet.
9
+ *
10
+ * A key is a head digit, the integer digits its head calls for, then a fraction
11
+ * that never ends in the zero digit; the smallest integer part (head and digits
12
+ * all zero) needs a fraction. See {@link generateFractionalKeyBetween}.
13
+ *
14
+ * Complexity: `O(|key|)`.
15
+ */
16
+ export declare function isFractionalKey(key: string, options?: FractionalKeyOptions): boolean;
17
+ /**
18
+ * Throws unless `key` is a well-formed fractional key under the alphabet: use
19
+ * it where keys come from storage or the network.
20
+ *
21
+ * Complexity: `O(|key|)`.
22
+ *
23
+ * @throws {FractionalKeyError} With the offset the check gave up at.
24
+ */
25
+ export declare function assertFractionalKey(key: string, options?: FractionalKeyOptions): void;
26
+ /**
27
+ * A key that sorts strictly between `lower` and `upper` under plain string
28
+ * comparison — fractional indexing, so that a user-ordered list inserts or
29
+ * moves one item by writing one key, with nothing renumbered.
30
+ *
31
+ * `null` is an open end: `(null, null)` is the first key, `(last, null)`
32
+ * appends and `(null, first)` prepends. Keys have an integer part and a
33
+ * fraction, and:
34
+ *
35
+ * - Appending or prepending steps the integer part, so `n` appends from one key
36
+ * grow it by `⌈log_base n⌉` digits at most (base 62: two digits hold 3 844
37
+ * appends, five hold 916 million). Past the last integer, which base 62
38
+ * reaches after `62^31` appends, keys keep growing in the fraction;
39
+ * - Between two keys, the result is the shortest key strictly between them — the
40
+ * next integer when there is room, otherwise the middle fraction digit — so
41
+ * it is never more than one code unit longer than the longer bound. Inserting
42
+ * again and again into the same gap halves it each time, adding a digit every
43
+ * `log₂ base` insertions (about 6 in base 62): spread a batch with
44
+ * {@link generateFractionalKeysBetween} instead.
45
+ *
46
+ * The result is deterministic: two replicas inserting into the same gap get the
47
+ * same key, which ties under string order. Break the tie by a second sort field
48
+ * (a record id), and generate a later key between the tied pair's neighbours.
49
+ *
50
+ * Complexity: `O(|lower| + |upper|)`.
51
+ *
52
+ * @param lower The key to sort after, or `null` for no lower bound.
53
+ * @param upper The key to sort before, or `null` for no upper bound.
54
+ * @throws {FractionalKeyError} If a bound is not a key under the alphabet.
55
+ * @throws {RangeError} If `lower` does not sort before `upper`.
56
+ */
57
+ export declare function generateFractionalKeyBetween(lower: string | null, upper: string | null, options?: FractionalKeyOptions): string;
58
+ /**
59
+ * `count` ascending keys strictly between `lower` and `upper` (`null` for an
60
+ * open end), for inserting a batch at one place.
61
+ *
62
+ * With an open end, the keys are consecutive appends (or prepends), as repeated
63
+ * {@link generateFractionalKeyBetween} calls would make them. Between two keys,
64
+ * they take the free integers first; the rest are fractions that divide each
65
+ * remaining gap evenly, at the coarsest precision holding them, so every key is
66
+ * at most `⌈log_base(count + 1)⌉` code units longer than the longer bound.
67
+ * `count = 1` gives the key `generateFractionalKeyBetween` gives. Regenerating
68
+ * a run of keys between its neighbours this way also shortens a run that grew
69
+ * long from many insertions into one gap.
70
+ *
71
+ * Complexity: `O(count · L)` for keys of length `L`, plus `O(w²)` once for a
72
+ * window of `w` digits where the bounds differ.
73
+ *
74
+ * @param lower The key to sort after, or `null` for no lower bound.
75
+ * @param upper The key to sort before, or `null` for no upper bound.
76
+ * @param count How many keys, a non-negative safe integer.
77
+ * @throws {FractionalKeyError} If a bound is not a key under the alphabet.
78
+ * @throws {RangeError} If `lower` does not sort before `upper`, or `count` is
79
+ * not a non-negative safe integer.
80
+ */
81
+ export declare function generateFractionalKeysBetween(lower: string | null, upper: string | null, count: number, options?: FractionalKeyOptions): string[];
82
+ //# sourceMappingURL=fractional-key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fractional-key.d.ts","sourceRoot":"","sources":["../../src/ordered/fractional-key.ts"],"names":[],"mappings":"AAaA,OAAO,EAEN,KAAK,qBAAqB,EAC1B,MAAM,8BAA8B,CAAC;AAEtC,+CAA+C;AAC/C,MAAM,MAAM,oBAAoB,GAAG;IAClC,sDAAsD;IACtD,QAAQ,CAAC,QAAQ,CAAC,EAAE,qBAAqB,CAAC;CAC1C,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC9B,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,oBAAoB,GAC5B,OAAO,CAKT;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAClC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,oBAAoB,GAC5B,IAAI,CAEN;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,4BAA4B,CAC3C,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,OAAO,CAAC,EAAE,oBAAoB,GAC5B,MAAM,CA4BR;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,6BAA6B,CAC5C,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE,oBAAoB,GAC5B,MAAM,EAAE,CAoEV"}
@@ -0,0 +1,199 @@
1
+ import { assertInteger } from "@ac-kit/core";
2
+ import { checkKey_, findKeyError_, fractionBetween_, fractionsBetween_, incrementInteger_, integerEnd_, keyAfter_, keyBefore_, zeroInteger_, } from "./_fractional-key.js";
3
+ import { BASE62_FRACTIONAL_KEY_ALPHABET, } from "./fractional-key-alphabet.js";
4
+ /**
5
+ * Whether `key` is a well-formed fractional key under the alphabet.
6
+ *
7
+ * A key is a head digit, the integer digits its head calls for, then a fraction
8
+ * that never ends in the zero digit; the smallest integer part (head and digits
9
+ * all zero) needs a fraction. See {@link generateFractionalKeyBetween}.
10
+ *
11
+ * Complexity: `O(|key|)`.
12
+ */
13
+ export function isFractionalKey(key, options) {
14
+ return (findKeyError_(key, options?.alphabet ?? BASE62_FRACTIONAL_KEY_ALPHABET) ===
15
+ null);
16
+ }
17
+ /**
18
+ * Throws unless `key` is a well-formed fractional key under the alphabet: use
19
+ * it where keys come from storage or the network.
20
+ *
21
+ * Complexity: `O(|key|)`.
22
+ *
23
+ * @throws {FractionalKeyError} With the offset the check gave up at.
24
+ */
25
+ export function assertFractionalKey(key, options) {
26
+ checkKey_(key, options?.alphabet ?? BASE62_FRACTIONAL_KEY_ALPHABET);
27
+ }
28
+ /**
29
+ * A key that sorts strictly between `lower` and `upper` under plain string
30
+ * comparison — fractional indexing, so that a user-ordered list inserts or
31
+ * moves one item by writing one key, with nothing renumbered.
32
+ *
33
+ * `null` is an open end: `(null, null)` is the first key, `(last, null)`
34
+ * appends and `(null, first)` prepends. Keys have an integer part and a
35
+ * fraction, and:
36
+ *
37
+ * - Appending or prepending steps the integer part, so `n` appends from one key
38
+ * grow it by `⌈log_base n⌉` digits at most (base 62: two digits hold 3 844
39
+ * appends, five hold 916 million). Past the last integer, which base 62
40
+ * reaches after `62^31` appends, keys keep growing in the fraction;
41
+ * - Between two keys, the result is the shortest key strictly between them — the
42
+ * next integer when there is room, otherwise the middle fraction digit — so
43
+ * it is never more than one code unit longer than the longer bound. Inserting
44
+ * again and again into the same gap halves it each time, adding a digit every
45
+ * `log₂ base` insertions (about 6 in base 62): spread a batch with
46
+ * {@link generateFractionalKeysBetween} instead.
47
+ *
48
+ * The result is deterministic: two replicas inserting into the same gap get the
49
+ * same key, which ties under string order. Break the tie by a second sort field
50
+ * (a record id), and generate a later key between the tied pair's neighbours.
51
+ *
52
+ * Complexity: `O(|lower| + |upper|)`.
53
+ *
54
+ * @param lower The key to sort after, or `null` for no lower bound.
55
+ * @param upper The key to sort before, or `null` for no upper bound.
56
+ * @throws {FractionalKeyError} If a bound is not a key under the alphabet.
57
+ * @throws {RangeError} If `lower` does not sort before `upper`.
58
+ */
59
+ export function generateFractionalKeyBetween(lower, upper, options) {
60
+ const alphabet = options?.alphabet ?? BASE62_FRACTIONAL_KEY_ALPHABET;
61
+ const lowerEnd = lower === null ? 0 : checkKey_(lower, alphabet);
62
+ const upperEnd = upper === null ? 0 : checkKey_(upper, alphabet);
63
+ if (lower === null) {
64
+ return upper === null
65
+ ? zeroInteger_(alphabet)
66
+ : keyBefore_(upper, upperEnd, alphabet);
67
+ }
68
+ if (upper === null) {
69
+ return keyAfter_(lower, lowerEnd, alphabet);
70
+ }
71
+ checkOrder_(lower, upper);
72
+ const lowerInteger = lower.slice(0, lowerEnd);
73
+ if (lowerInteger === upper.slice(0, upperEnd)) {
74
+ return (lowerInteger +
75
+ fractionBetween_(lower.slice(lowerEnd), upper.slice(upperEnd), alphabet));
76
+ }
77
+ // The integers differ, so `lowerInteger` has a successor.
78
+ const next = incrementInteger_(lowerInteger, alphabet);
79
+ return next < upper
80
+ ? next
81
+ : lowerInteger + fractionBetween_(lower.slice(lowerEnd), null, alphabet);
82
+ }
83
+ /**
84
+ * `count` ascending keys strictly between `lower` and `upper` (`null` for an
85
+ * open end), for inserting a batch at one place.
86
+ *
87
+ * With an open end, the keys are consecutive appends (or prepends), as repeated
88
+ * {@link generateFractionalKeyBetween} calls would make them. Between two keys,
89
+ * they take the free integers first; the rest are fractions that divide each
90
+ * remaining gap evenly, at the coarsest precision holding them, so every key is
91
+ * at most `⌈log_base(count + 1)⌉` code units longer than the longer bound.
92
+ * `count = 1` gives the key `generateFractionalKeyBetween` gives. Regenerating
93
+ * a run of keys between its neighbours this way also shortens a run that grew
94
+ * long from many insertions into one gap.
95
+ *
96
+ * Complexity: `O(count · L)` for keys of length `L`, plus `O(w²)` once for a
97
+ * window of `w` digits where the bounds differ.
98
+ *
99
+ * @param lower The key to sort after, or `null` for no lower bound.
100
+ * @param upper The key to sort before, or `null` for no upper bound.
101
+ * @param count How many keys, a non-negative safe integer.
102
+ * @throws {FractionalKeyError} If a bound is not a key under the alphabet.
103
+ * @throws {RangeError} If `lower` does not sort before `upper`, or `count` is
104
+ * not a non-negative safe integer.
105
+ */
106
+ export function generateFractionalKeysBetween(lower, upper, count, options) {
107
+ const alphabet = options?.alphabet ?? BASE62_FRACTIONAL_KEY_ALPHABET;
108
+ assertInteger(count, "count", 0);
109
+ const lowerEnd = lower === null ? 0 : checkKey_(lower, alphabet);
110
+ const upperEnd = upper === null ? 0 : checkKey_(upper, alphabet);
111
+ if (count === 0) {
112
+ if (lower !== null && upper !== null) {
113
+ checkOrder_(lower, upper);
114
+ }
115
+ return [];
116
+ }
117
+ if (lower === null || upper === null) {
118
+ return openEndedKeys_(lower, lowerEnd, upper, upperEnd, count, alphabet);
119
+ }
120
+ checkOrder_(lower, upper);
121
+ const lowerInteger = lower.slice(0, lowerEnd);
122
+ const upperInteger = upper.slice(0, upperEnd);
123
+ const lowerFraction = lower.slice(lowerEnd);
124
+ if (lowerInteger === upperInteger) {
125
+ return prefixAll_(lowerInteger, fractionsBetween_(lowerFraction, upper.slice(upperEnd), count, alphabet));
126
+ }
127
+ // The integers strictly between the bounds, as many as are wanted; the last
128
+ // integer has no successor, but can be `upper`'s own.
129
+ const integers = [];
130
+ let next = incrementInteger_(lowerInteger, alphabet);
131
+ while (integers.length < count && next !== null && next < upper) {
132
+ integers.push(next);
133
+ next = incrementInteger_(next, alphabet);
134
+ }
135
+ if (integers.length === count) {
136
+ return integers;
137
+ }
138
+ // Fewer integers than keys: share the rest evenly between the gaps around
139
+ // them. The last integer may be `upper`'s own, below `upper`'s fraction.
140
+ const gapCount = integers.length + 1;
141
+ const share = Math.floor((count - integers.length) / gapCount);
142
+ const extra = (count - integers.length) % gapCount;
143
+ const keys = [];
144
+ for (let gap = 0; gap < gapCount; gap++) {
145
+ if (gap > 0) {
146
+ keys.push(integers[gap - 1]);
147
+ }
148
+ const keysInGap = share +
149
+ Math.floor(((gap + 1) * extra) / gapCount) -
150
+ Math.floor((gap * extra) / gapCount);
151
+ if (keysInGap === 0) {
152
+ continue;
153
+ }
154
+ const integer = gap === 0 ? lowerInteger : integers[gap - 1];
155
+ const fractions = fractionsBetween_(gap === 0 ? lowerFraction : "", integer === upperInteger ? upper.slice(upperEnd) : null, keysInGap, alphabet);
156
+ for (const fraction of fractions) {
157
+ keys.push(integer + fraction);
158
+ }
159
+ }
160
+ return keys;
161
+ }
162
+ function checkOrder_(lower, upper) {
163
+ if (!(lower < upper)) {
164
+ throw new RangeError(`The lower key must sort before the upper key, got ${JSON.stringify(lower)} and ${JSON.stringify(upper)}`);
165
+ }
166
+ }
167
+ function openEndedKeys_(lower, lowerEnd, upper, upperEnd, count, alphabet) {
168
+ const keys = new Array(count);
169
+ if (upper === null) {
170
+ let key = lower ?? zeroInteger_(alphabet);
171
+ let first = 0;
172
+ if (lower === null) {
173
+ keys[0] = key;
174
+ first = 1;
175
+ }
176
+ let end = lower === null ? integerEnd_(key, alphabet) : lowerEnd;
177
+ for (let index = first; index < count; index++) {
178
+ key = keyAfter_(key, end, alphabet);
179
+ end = integerEnd_(key, alphabet);
180
+ keys[index] = key;
181
+ }
182
+ return keys;
183
+ }
184
+ let key = upper;
185
+ let end = upperEnd;
186
+ for (let index = count - 1; index >= 0; index--) {
187
+ key = keyBefore_(key, end, alphabet);
188
+ end = integerEnd_(key, alphabet);
189
+ keys[index] = key;
190
+ }
191
+ return keys;
192
+ }
193
+ function prefixAll_(prefix, fractions) {
194
+ for (let index = 0; index < fractions.length; index++) {
195
+ fractions[index] = prefix + fractions[index];
196
+ }
197
+ return fractions;
198
+ }
199
+ //# sourceMappingURL=fractional-key.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fractional-key.js","sourceRoot":"","sources":["../../src/ordered/fractional-key.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,OAAO,EACN,SAAS,EACT,aAAa,EACb,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,SAAS,EACT,UAAU,EACV,YAAY,GACZ,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACN,8BAA8B,GAE9B,MAAM,8BAA8B,CAAC;AAQtC;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAC9B,GAAW,EACX,OAA8B;IAE9B,OAAO,CACN,aAAa,CAAC,GAAG,EAAE,OAAO,EAAE,QAAQ,IAAI,8BAA8B,CAAC;QACvE,IAAI,CACJ,CAAC;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,CAClC,GAAW,EACX,OAA8B;IAE9B,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,QAAQ,IAAI,8BAA8B,CAAC,CAAC;AACrE,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,UAAU,4BAA4B,CAC3C,KAAoB,EACpB,KAAoB,EACpB,OAA8B;IAE9B,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,8BAA8B,CAAC;IACrE,MAAM,QAAQ,GAAG,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IACjE,MAAM,QAAQ,GAAG,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAEjE,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QACpB,OAAO,KAAK,KAAK,IAAI;YACpB,CAA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I,KAAK,GAAG,KAAK,EAAE,KAAK,GAAG,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC;YAChD,GAAG,GAAG,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;YACpC,GAAG,GAAG,WAAW,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;YACjC,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC;QACnB,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC;IAED,IAAI,GAAG,GAAG,KAAK,CAAC;IAChB,IAAI,GAAG,GAAG,QAAQ,CAAC;IACnB,KAAK,IAAI,KAAK,GAAG,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;QACjD,GAAG,GAAG,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;QACrC,GAAG,GAAG,WAAW,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;QACjC,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC;IACnB,CAAC;IACD,OAAO,IAAI,CAAC;AACb,CAAC;AAED,SAAS,UAAU,CAAC,MAAc,EAAE,SAAmB;IACtD,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QACvD,SAAS,CAAC,KAAK,CAAC,GAAG,MAAM,GAAG,SAAS,CAAC,KAAK,CAAE,CAAC;IAC/C,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC"}
@@ -0,0 +1,33 @@
1
+ import type { Comparator } from "@ac-kit/core";
2
+ export type IsSortedOptions = {
3
+ /**
4
+ * Also reject two neighbours `compare` finds equivalent, so the items must be
5
+ * strictly increasing — the precondition of a sorted set rather than of a
6
+ * sorted list. Default `false`.
7
+ */
8
+ strict?: boolean;
9
+ };
10
+ /**
11
+ * Whether `items` are in non-decreasing order under `compare` — the
12
+ * precondition `bisect`, `isInSortedIntervals` and every other search over a
13
+ * sorted collection assumes and none of them checks, for an assertion at a
14
+ * trust boundary or a test.
15
+ *
16
+ * Compares each item with the one before it and stops at the first pair out of
17
+ * order, so it reads an iterable once and never sorts or copies it.
18
+ *
19
+ * Time complexity: O(n), at most `n − 1` calls to `compare`. Memory: O(1).
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * isSorted([1, 2, 2, 3], compareNaturalAscending); // true
24
+ * isSorted([1, 2, 2, 3], compareNaturalAscending, { strict: true }); // false
25
+ * ```;
26
+ *
27
+ * @param items - The items, in order; an empty or one-item input is sorted.
28
+ * @param compare - The ordering the items should follow.
29
+ * @param options - Whether equivalent neighbours are allowed.
30
+ * @returns `true` when no item is ordered before the one preceding it.
31
+ */
32
+ export declare function isSorted<T>(items: Iterable<T>, compare: Comparator<T>, options?: IsSortedOptions): boolean;
33
+ //# sourceMappingURL=is-sorted.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"is-sorted.d.ts","sourceRoot":"","sources":["../../src/ordered/is-sorted.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,MAAM,MAAM,eAAe,GAAG;IAC7B;;;;OAIG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EACzB,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,EAClB,OAAO,EAAE,UAAU,CAAC,CAAC,CAAC,EACtB,OAAO,GAAE,eAAoB,GAC3B,OAAO,CAeT"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Whether `items` are in non-decreasing order under `compare` — the
3
+ * precondition `bisect`, `isInSortedIntervals` and every other search over a
4
+ * sorted collection assumes and none of them checks, for an assertion at a
5
+ * trust boundary or a test.
6
+ *
7
+ * Compares each item with the one before it and stops at the first pair out of
8
+ * order, so it reads an iterable once and never sorts or copies it.
9
+ *
10
+ * Time complexity: O(n), at most `n − 1` calls to `compare`. Memory: O(1).
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * isSorted([1, 2, 2, 3], compareNaturalAscending); // true
15
+ * isSorted([1, 2, 2, 3], compareNaturalAscending, { strict: true }); // false
16
+ * ```;
17
+ *
18
+ * @param items - The items, in order; an empty or one-item input is sorted.
19
+ * @param compare - The ordering the items should follow.
20
+ * @param options - Whether equivalent neighbours are allowed.
21
+ * @returns `true` when no item is ordered before the one preceding it.
22
+ */
23
+ export function isSorted(items, compare, options = {}) {
24
+ const strict = options.strict ?? false;
25
+ let previous;
26
+ let hasPrevious = false;
27
+ for (const item of items) {
28
+ if (hasPrevious) {
29
+ const order = compare(previous, item);
30
+ if (order > 0 || (strict && order === 0)) {
31
+ return false;
32
+ }
33
+ }
34
+ previous = item;
35
+ hasPrevious = true;
36
+ }
37
+ return true;
38
+ }
39
+ //# sourceMappingURL=is-sorted.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"is-sorted.js","sourceRoot":"","sources":["../../src/ordered/is-sorted.ts"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,QAAQ,CACvB,KAAkB,EAClB,OAAsB,EACtB,OAAO,GAAoB,EAAE;IAE7B,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,KAAK,CAAC;IACvC,IAAI,QAAW,CAAC;IAChB,IAAI,WAAW,GAAG,KAAK,CAAC;IACxB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,IAAI,WAAW,EAAE,CAAC;YACjB,MAAM,KAAK,GAAG,OAAO,CAAC,QAAS,EAAE,IAAI,CAAC,CAAC;YACvC,IAAI,KAAK,GAAG,CAAC,IAAI,CAAC,MAAM,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE,CAAC;gBAC1C,OAAO,KAAK,CAAC;YACd,CAAC;QACF,CAAC;QACD,QAAQ,GAAG,IAAI,CAAC;QAChB,WAAW,GAAG,IAAI,CAAC;IACpB,CAAC;IACD,OAAO,IAAI,CAAC;AACb,CAAC"}
@@ -0,0 +1,26 @@
1
+ import { type RandomFn } from "@ac-kit/core";
2
+ /**
3
+ * Draws `size` distinct positions' elements of `items`, uniformly: every
4
+ * ordered selection of `size` positions is equally likely, so the result is
5
+ * also in random order. A raffle, a random subset for review, a test sample.
6
+ *
7
+ * The first `size` steps of a Fisher–Yates shuffle, with the positions it would
8
+ * have swapped kept in a sparse `Map` rather than in a copy of `items`, so the
9
+ * cost follows the sample, not the input: drawing 10 of a million is 10 steps.
10
+ *
11
+ * Time complexity: O(size), `size` calls to `random`. Memory: O(size).
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * sampleWithoutReplacement(entrants, 3, Math.random); // three winners
16
+ * ```;
17
+ *
18
+ * @param items - The population; not copied or modified. Equal elements at
19
+ * different positions are distinct draws.
20
+ * @param size - How many to draw, an integer in `[0, items.length]`.
21
+ * @param random - A source in `[0, 1)`, called once per draw.
22
+ * @returns A fresh array of `size` elements.
23
+ * @throws {RangeError} When `size` is not an integer in `[0, items.length]`.
24
+ */
25
+ export declare function sampleWithoutReplacement<T>(items: readonly T[], size: number, random: RandomFn): T[];
26
+ //# sourceMappingURL=sample-without-replacement.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sample-without-replacement.d.ts","sourceRoot":"","sources":["../../src/sample/sample-without-replacement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAC;AAI5D;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,wBAAwB,CAAC,CAAC,EACzC,KAAK,EAAE,SAAS,CAAC,EAAE,EACnB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,QAAQ,GACd,CAAC,EAAE,CAcL"}
@@ -0,0 +1,41 @@
1
+ import { assertInteger } from "@ac-kit/core";
2
+ import { randomIndex } from "./_random-index.js";
3
+ /**
4
+ * Draws `size` distinct positions' elements of `items`, uniformly: every
5
+ * ordered selection of `size` positions is equally likely, so the result is
6
+ * also in random order. A raffle, a random subset for review, a test sample.
7
+ *
8
+ * The first `size` steps of a Fisher–Yates shuffle, with the positions it would
9
+ * have swapped kept in a sparse `Map` rather than in a copy of `items`, so the
10
+ * cost follows the sample, not the input: drawing 10 of a million is 10 steps.
11
+ *
12
+ * Time complexity: O(size), `size` calls to `random`. Memory: O(size).
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * sampleWithoutReplacement(entrants, 3, Math.random); // three winners
17
+ * ```;
18
+ *
19
+ * @param items - The population; not copied or modified. Equal elements at
20
+ * different positions are distinct draws.
21
+ * @param size - How many to draw, an integer in `[0, items.length]`.
22
+ * @param random - A source in `[0, 1)`, called once per draw.
23
+ * @returns A fresh array of `size` elements.
24
+ * @throws {RangeError} When `size` is not an integer in `[0, items.length]`.
25
+ */
26
+ export function sampleWithoutReplacement(items, size, random) {
27
+ const length = items.length;
28
+ assertInteger(size, "sampleWithoutReplacement: size", 0, length);
29
+ // displaced.get(p): the position whose element a swap left at position p;
30
+ // absent means p still holds its own.
31
+ const displaced = new Map();
32
+ const sample = Array.from({ length: size });
33
+ for (let step = 0; step < size; step++) {
34
+ const pick = step + randomIndex(length - step, random);
35
+ const picked = displaced.get(pick) ?? pick;
36
+ sample[step] = items[picked];
37
+ displaced.set(pick, displaced.get(step) ?? step);
38
+ }
39
+ return sample;
40
+ }
41
+ //# sourceMappingURL=sample-without-replacement.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sample-without-replacement.js","sourceRoot":"","sources":["../../src/sample/sample-without-replacement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAiB,MAAM,cAAc,CAAC;AAE5D,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,wBAAwB,CACvC,KAAmB,EACnB,IAAY,EACZ,MAAgB;IAEhB,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAC5B,aAAa,CAAC,IAAI,EAAE,gCAAgC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;IACjE,0EAA0E;IAC1E,sCAAsC;IACtC,MAAM,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC5C,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IAC/C,KAAK,IAAI,IAAI,GAAG,CAAC,EAAE,IAAI,GAAG,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC;QACxC,MAAM,IAAI,GAAG,IAAI,GAAG,WAAW,CAAC,MAAM,GAAG,IAAI,EAAE,MAAM,CAAC,CAAC;QACvD,MAAM,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC;QAC3C,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAE,CAAC;QAC9B,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC;IAClD,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC"}
@@ -1,4 +1,4 @@
1
- import { Callable } from "@ac-kit/core";
1
+ import type { RandomFn } from "@ac-kit/core";
2
2
  export type ShuffleAlgorithm = "fisherYates" | "sattolo";
3
3
  export type ShuffleOptions = {
4
4
  /**
@@ -7,7 +7,7 @@ export type ShuffleOptions = {
7
7
  *
8
8
  * Defaults to `Math.random` if not provided.
9
9
  */
10
- rand?: Callable<[], number>;
10
+ random?: RandomFn;
11
11
  /**
12
12
  * The shuffle algorithm to use.
13
13
  *
@@ -1 +1 @@
1
- {"version":3,"file":"shuffle.d.ts","sourceRoot":"","sources":["../../src/sample/shuffle.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAIxC,MAAM,MAAM,gBAAgB,GAAG,aAAa,GAAG,SAAS,CAAC;AAEzD,MAAM,MAAM,cAAc,GAAG;IAC5B;;;;;OAKG;IACH,IAAI,CAAC,EAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;IAE5B;;;;OAIG;IACH,SAAS,CAAC,EAAE,gBAAgB,CAAC;CAC7B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,EAAE,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,CAAC,EAAE,CAuB7E"}
1
+ {"version":3,"file":"shuffle.d.ts","sourceRoot":"","sources":["../../src/sample/shuffle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAI7C,MAAM,MAAM,gBAAgB,GAAG,aAAa,GAAG,SAAS,CAAC;AAEzD,MAAM,MAAM,cAAc,GAAG;IAC5B;;;;;OAKG;IACH,MAAM,CAAC,EAAE,QAAQ,CAAC;IAElB;;;;OAIG;IACH,SAAS,CAAC,EAAE,gBAAgB,CAAC;CAC7B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,EAAE,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,CAAC,EAAE,CAuB7E"}
@@ -12,14 +12,14 @@ import { randomIndex } from "./_random-index.js";
12
12
  * @returns A new array containing the shuffled elements of the input.
13
13
  */
14
14
  export function shuffle(items, options) {
15
- const rand = options?.rand ?? Math.random;
15
+ const random = options?.random ?? Math.random;
16
16
  const algorithm = options?.algorithm ?? "fisherYates";
17
17
  const randomize = (i) => {
18
18
  if (algorithm === "sattolo") {
19
- return randomIndex(i, rand);
19
+ return randomIndex(i, random);
20
20
  }
21
21
  else {
22
- return randomIndex(i + 1, rand);
22
+ return randomIndex(i + 1, random);
23
23
  }
24
24
  };
25
25
  const out = items.slice();
@@ -1 +1 @@
1
- {"version":3,"file":"shuffle.js","sourceRoot":"","sources":["../../src/sample/shuffle.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAqBjD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,OAAO,CAAI,KAAmB,EAAE,OAAwB;IACvE,MAAM,IAAI,GAAG,OAAO,EAAE,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC;IAC1C,MAAM,SAAS,GAAG,OAAO,EAAE,SAAS,IAAI,aAAa,CAAC;IAEtD,MAAM,SAAS,GAAG,CAAC,CAAS,EAAU,EAAE;QACvC,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;YAC7B,OAAO,WAAW,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QAC7B,CAAC;aAAM,CAAC;YACP,OAAO,WAAW,CAAC,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC;QACjC,CAAC;IACF,CAAC,CAAC;IAEF,MAAM,GAAG,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC;IAE1B,KAAK,IAAI,CAAC,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QACzC,MAAM,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;QAEvB,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,CAAE,CAAC;QACpB,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAE,CAAC;QACjB,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;IACd,CAAC;IAED,OAAO,GAAG,CAAC;AACZ,CAAC"}
1
+ {"version":3,"file":"shuffle.js","sourceRoot":"","sources":["../../src/sample/shuffle.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAqBjD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,OAAO,CAAI,KAAmB,EAAE,OAAwB;IACvE,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC;IAC9C,MAAM,SAAS,GAAG,OAAO,EAAE,SAAS,IAAI,aAAa,CAAC;IAEtD,MAAM,SAAS,GAAG,CAAC,CAAS,EAAU,EAAE;QACvC,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;YAC7B,OAAO,WAAW,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;aAAM,CAAC;YACP,OAAO,WAAW,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC;QACnC,CAAC;IACF,CAAC,CAAC;IAEF,MAAM,GAAG,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC;IAE1B,KAAK,IAAI,CAAC,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QACzC,MAAM,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;QAEvB,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,CAAE,CAAC;QACpB,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAE,CAAC;QACjB,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;IACd,CAAC;IAED,OAAO,GAAG,CAAC;AACZ,CAAC"}
@@ -0,0 +1,29 @@
1
+ import { type RandomFn } from "@ac-kit/core";
2
+ /**
3
+ * Picks the position of one element of `items` with probability proportional to
4
+ * its weight — the position-returning form of {@link weightedChoice}, for a
5
+ * caller holding parallel arrays.
6
+ *
7
+ * Reads every weight once, then walks the cumulative weights to where one draw
8
+ * of `random` lands. For many draws from one distribution, a precomputed alias
9
+ * table (Vose) answers each in O(1) instead.
10
+ *
11
+ * Time complexity: O(n), one call to `random`. Memory: O(n) for the weights,
12
+ * read once so `weightOf` need not be cheap or repeatable.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * weightedChoiceIndex(["rare", "common"], (item) => (item === "rare" ? 1 : 9), random);
17
+ * // 1 nine times in ten
18
+ * ```;
19
+ *
20
+ * @param items - The candidates.
21
+ * @param weightOf - The weight of an item, a finite number `≥ 0`; an item of
22
+ * weight `0` is never picked.
23
+ * @param random - A source in `[0, 1)`; not called when no weight is positive.
24
+ * @returns A position, or `-1` when `items` is empty or every weight is `0`.
25
+ * @throws {RangeError} When a weight is negative, `NaN` or infinite, or the
26
+ * total weight overflows to `Infinity`.
27
+ */
28
+ export declare function weightedChoiceIndex<T>(items: readonly T[], weightOf: (item: T, index: number) => number, random: RandomFn): number;
29
+ //# sourceMappingURL=weighted-choice-index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"weighted-choice-index.d.ts","sourceRoot":"","sources":["../../src/sample/weighted-choice-index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EACpC,KAAK,EAAE,SAAS,CAAC,EAAE,EACnB,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,EAC5C,MAAM,EAAE,QAAQ,GACd,MAAM,CAoCR"}
@@ -0,0 +1,62 @@
1
+ import { describeValue } from "@ac-kit/core";
2
+ /**
3
+ * Picks the position of one element of `items` with probability proportional to
4
+ * its weight — the position-returning form of {@link weightedChoice}, for a
5
+ * caller holding parallel arrays.
6
+ *
7
+ * Reads every weight once, then walks the cumulative weights to where one draw
8
+ * of `random` lands. For many draws from one distribution, a precomputed alias
9
+ * table (Vose) answers each in O(1) instead.
10
+ *
11
+ * Time complexity: O(n), one call to `random`. Memory: O(n) for the weights,
12
+ * read once so `weightOf` need not be cheap or repeatable.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * weightedChoiceIndex(["rare", "common"], (item) => (item === "rare" ? 1 : 9), random);
17
+ * // 1 nine times in ten
18
+ * ```;
19
+ *
20
+ * @param items - The candidates.
21
+ * @param weightOf - The weight of an item, a finite number `≥ 0`; an item of
22
+ * weight `0` is never picked.
23
+ * @param random - A source in `[0, 1)`; not called when no weight is positive.
24
+ * @returns A position, or `-1` when `items` is empty or every weight is `0`.
25
+ * @throws {RangeError} When a weight is negative, `NaN` or infinite, or the
26
+ * total weight overflows to `Infinity`.
27
+ */
28
+ export function weightedChoiceIndex(items, weightOf, random) {
29
+ const length = items.length;
30
+ const weights = new Float64Array(length);
31
+ let total = 0;
32
+ let lastPositive = -1;
33
+ for (let index = 0; index < length; index++) {
34
+ const weight = weightOf(items[index], index);
35
+ if (!(weight >= 0 && weight < Infinity)) {
36
+ throw new RangeError(`weightedChoiceIndex: the weight of items[${index}] must be a finite number ≥ 0, got ${describeValue(weight)}`);
37
+ }
38
+ weights[index] = weight;
39
+ total += weight;
40
+ if (weight > 0) {
41
+ lastPositive = index;
42
+ }
43
+ }
44
+ if (total === Infinity) {
45
+ throw new RangeError("weightedChoiceIndex: the total weight overflows");
46
+ }
47
+ if (lastPositive < 0) {
48
+ return -1;
49
+ }
50
+ const target = random() * total;
51
+ let cumulative = 0;
52
+ for (let index = 0; index < lastPositive; index++) {
53
+ cumulative += weights[index];
54
+ // `>` rather than `≥` steps over zero weights, which add nothing.
55
+ if (cumulative > target) {
56
+ return index;
57
+ }
58
+ }
59
+ // Rounding in the running sum can leave `target` just past it.
60
+ return lastPositive;
61
+ }
62
+ //# sourceMappingURL=weighted-choice-index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"weighted-choice-index.js","sourceRoot":"","sources":["../../src/sample/weighted-choice-index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAiB,MAAM,cAAc,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,UAAU,mBAAmB,CAClC,KAAmB,EACnB,QAA4C,EAC5C,M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QACd,CAAC;IACF,CAAC;IACD,+DAA+D;IAC/D,OAAO,YAAY,CAAC;AACrB,CAAC"}
@@ -0,0 +1,28 @@
1
+ import type { RandomFn } from "@ac-kit/core";
2
+ /**
3
+ * Picks one element of `items` with probability proportional to its weight: a
4
+ * loot table, a weighted A/B split, a sampled next token.
5
+ *
6
+ * One draw of {@link weightedChoiceIndex}, whose contract it shares. For many
7
+ * draws from one distribution, a precomputed alias table (Vose) answers each in
8
+ * O(1) instead.
9
+ *
10
+ * Time complexity: O(n), one call to `random`. Memory: O(n).
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * weightedChoice(prizes, (prize) => prize.odds, Math.random);
15
+ * ```;
16
+ *
17
+ * @param items - The candidates.
18
+ * @param weightOf - The weight of an item, a finite number `≥ 0`; an item of
19
+ * weight `0` is never picked.
20
+ * @param random - A source in `[0, 1)`; not called when no weight is positive.
21
+ * @returns An element, or `undefined` when `items` is empty or every weight is
22
+ * `0` (so an array that holds `undefined` cannot tell the two apart: use
23
+ * {@link weightedChoiceIndex}).
24
+ * @throws {RangeError} When a weight is negative, `NaN` or infinite, or the
25
+ * total weight overflows to `Infinity`.
26
+ */
27
+ export declare function weightedChoice<T>(items: readonly T[], weightOf: (item: T, index: number) => number, random: RandomFn): T | undefined;
28
+ //# sourceMappingURL=weighted-choice.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"weighted-choice.d.ts","sourceRoot":"","sources":["../../src/sample/weighted-choice.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAI7C;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAC/B,KAAK,EAAE,SAAS,CAAC,EAAE,EACnB,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,EAC5C,MAAM,EAAE,QAAQ,GACd,CAAC,GAAG,SAAS,CAGf"}