@procedures/collections 0.0.0-stage → 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 (205) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +21 -0
  3. package/README.md +394 -2
  4. package/dist/.tsbuildinfo +1 -0
  5. package/dist/async/async-queue.d.ts +155 -0
  6. package/dist/async/async-queue.d.ts.map +1 -0
  7. package/dist/async/async-queue.js +342 -0
  8. package/dist/async/async-queue.js.map +1 -0
  9. package/dist/async/channels.d.ts +188 -0
  10. package/dist/async/channels.d.ts.map +1 -0
  11. package/dist/async/channels.js +314 -0
  12. package/dist/async/channels.js.map +1 -0
  13. package/dist/behaviors/bounded.d.ts +79 -0
  14. package/dist/behaviors/bounded.d.ts.map +1 -0
  15. package/dist/behaviors/bounded.js +384 -0
  16. package/dist/behaviors/bounded.js.map +1 -0
  17. package/dist/behaviors/composite.d.ts +17 -0
  18. package/dist/behaviors/composite.d.ts.map +1 -0
  19. package/dist/behaviors/composite.js +93 -0
  20. package/dist/behaviors/composite.js.map +1 -0
  21. package/dist/behaviors/evented.d.ts +154 -0
  22. package/dist/behaviors/evented.d.ts.map +1 -0
  23. package/dist/behaviors/evented.js +299 -0
  24. package/dist/behaviors/evented.js.map +1 -0
  25. package/dist/behaviors/lru.d.ts +84 -0
  26. package/dist/behaviors/lru.d.ts.map +1 -0
  27. package/dist/behaviors/lru.js +376 -0
  28. package/dist/behaviors/lru.js.map +1 -0
  29. package/dist/behaviors/readonly.d.ts +73 -0
  30. package/dist/behaviors/readonly.d.ts.map +1 -0
  31. package/dist/behaviors/readonly.js +177 -0
  32. package/dist/behaviors/readonly.js.map +1 -0
  33. package/dist/behaviors/safe.d.ts +163 -0
  34. package/dist/behaviors/safe.d.ts.map +1 -0
  35. package/dist/behaviors/safe.js +176 -0
  36. package/dist/behaviors/safe.js.map +1 -0
  37. package/dist/behaviors/synchronized.d.ts +88 -0
  38. package/dist/behaviors/synchronized.d.ts.map +1 -0
  39. package/dist/behaviors/synchronized.js +285 -0
  40. package/dist/behaviors/synchronized.js.map +1 -0
  41. package/dist/behaviors/ttl.d.ts +118 -0
  42. package/dist/behaviors/ttl.d.ts.map +1 -0
  43. package/dist/behaviors/ttl.js +354 -0
  44. package/dist/behaviors/ttl.js.map +1 -0
  45. package/dist/contracts/model.d.ts +29 -0
  46. package/dist/contracts/model.d.ts.map +1 -0
  47. package/dist/contracts/model.js +26 -0
  48. package/dist/contracts/model.js.map +1 -0
  49. package/dist/core/effects.d.ts +176 -0
  50. package/dist/core/effects.d.ts.map +1 -0
  51. package/dist/core/effects.js +180 -0
  52. package/dist/core/effects.js.map +1 -0
  53. package/dist/core/events.d.ts +192 -0
  54. package/dist/core/events.d.ts.map +1 -0
  55. package/dist/core/events.js +291 -0
  56. package/dist/core/events.js.map +1 -0
  57. package/dist/core/middleware.d.ts +231 -0
  58. package/dist/core/middleware.d.ts.map +1 -0
  59. package/dist/core/middleware.js +161 -0
  60. package/dist/core/middleware.js.map +1 -0
  61. package/dist/core/policies.d.ts +220 -0
  62. package/dist/core/policies.d.ts.map +1 -0
  63. package/dist/core/policies.js +48 -0
  64. package/dist/core/policies.js.map +1 -0
  65. package/dist/core/traits.d.ts +142 -0
  66. package/dist/core/traits.d.ts.map +1 -0
  67. package/dist/core/traits.js +8 -0
  68. package/dist/core/traits.js.map +1 -0
  69. package/dist/fx/collectors.d.ts +193 -0
  70. package/dist/fx/collectors.d.ts.map +1 -0
  71. package/dist/fx/collectors.js +375 -0
  72. package/dist/fx/collectors.js.map +1 -0
  73. package/dist/fx/iter.d.ts +166 -0
  74. package/dist/fx/iter.d.ts.map +1 -0
  75. package/dist/fx/iter.js +421 -0
  76. package/dist/fx/iter.js.map +1 -0
  77. package/dist/impl/array-deque.d.ts +112 -0
  78. package/dist/impl/array-deque.d.ts.map +1 -0
  79. package/dist/impl/array-deque.js +380 -0
  80. package/dist/impl/array-deque.js.map +1 -0
  81. package/dist/impl/array-list.d.ts +101 -0
  82. package/dist/impl/array-list.d.ts.map +1 -0
  83. package/dist/impl/array-list.js +387 -0
  84. package/dist/impl/array-list.js.map +1 -0
  85. package/dist/impl/hash-map.d.ts +149 -0
  86. package/dist/impl/hash-map.d.ts.map +1 -0
  87. package/dist/impl/hash-map.js +473 -0
  88. package/dist/impl/hash-map.js.map +1 -0
  89. package/dist/impl/hash-set.d.ts +125 -0
  90. package/dist/impl/hash-set.d.ts.map +1 -0
  91. package/dist/impl/hash-set.js +264 -0
  92. package/dist/impl/hash-set.js.map +1 -0
  93. package/dist/impl/linked-hash-map.d.ts +141 -0
  94. package/dist/impl/linked-hash-map.d.ts.map +1 -0
  95. package/dist/impl/linked-hash-map.js +442 -0
  96. package/dist/impl/linked-hash-map.js.map +1 -0
  97. package/dist/impl/linked-list.d.ts +109 -0
  98. package/dist/impl/linked-list.d.ts.map +1 -0
  99. package/dist/impl/linked-list.js +494 -0
  100. package/dist/impl/linked-list.js.map +1 -0
  101. package/dist/impl/priority-queue.d.ts +139 -0
  102. package/dist/impl/priority-queue.d.ts.map +1 -0
  103. package/dist/impl/priority-queue.js +343 -0
  104. package/dist/impl/priority-queue.js.map +1 -0
  105. package/dist/impl/tree-map.d.ts +153 -0
  106. package/dist/impl/tree-map.d.ts.map +1 -0
  107. package/dist/impl/tree-map.js +788 -0
  108. package/dist/impl/tree-map.js.map +1 -0
  109. package/dist/impl/tree-set.d.ts +112 -0
  110. package/dist/impl/tree-set.d.ts.map +1 -0
  111. package/dist/impl/tree-set.js +374 -0
  112. package/dist/impl/tree-set.js.map +1 -0
  113. package/dist/index.d.ts +106 -0
  114. package/dist/index.d.ts.map +1 -0
  115. package/dist/index.js +139 -0
  116. package/dist/index.js.map +1 -0
  117. package/dist/interfaces/collection.d.ts +119 -0
  118. package/dist/interfaces/collection.d.ts.map +1 -0
  119. package/dist/interfaces/collection.js +8 -0
  120. package/dist/interfaces/collection.js.map +1 -0
  121. package/dist/interfaces/list.d.ts +247 -0
  122. package/dist/interfaces/list.d.ts.map +1 -0
  123. package/dist/interfaces/list.js +8 -0
  124. package/dist/interfaces/list.js.map +1 -0
  125. package/dist/interfaces/map.d.ts +344 -0
  126. package/dist/interfaces/map.d.ts.map +1 -0
  127. package/dist/interfaces/map.js +8 -0
  128. package/dist/interfaces/map.js.map +1 -0
  129. package/dist/interfaces/queue.d.ts +304 -0
  130. package/dist/interfaces/queue.d.ts.map +1 -0
  131. package/dist/interfaces/queue.js +8 -0
  132. package/dist/interfaces/queue.js.map +1 -0
  133. package/dist/interfaces/set.d.ts +137 -0
  134. package/dist/interfaces/set.d.ts.map +1 -0
  135. package/dist/interfaces/set.js +8 -0
  136. package/dist/interfaces/set.js.map +1 -0
  137. package/dist/register.d.ts +8 -0
  138. package/dist/register.d.ts.map +1 -0
  139. package/dist/register.js +8 -0
  140. package/dist/register.js.map +1 -0
  141. package/dist/storage/index.d.ts +15 -0
  142. package/dist/storage/index.d.ts.map +1 -0
  143. package/dist/storage/index.js +14 -0
  144. package/dist/storage/index.js.map +1 -0
  145. package/dist/storage/interface.d.ts +141 -0
  146. package/dist/storage/interface.d.ts.map +1 -0
  147. package/dist/storage/interface.js +23 -0
  148. package/dist/storage/interface.js.map +1 -0
  149. package/dist/storage/memory.d.ts +68 -0
  150. package/dist/storage/memory.d.ts.map +1 -0
  151. package/dist/storage/memory.js +154 -0
  152. package/dist/storage/memory.js.map +1 -0
  153. package/dist/utils/defaults.d.ts +135 -0
  154. package/dist/utils/defaults.d.ts.map +1 -0
  155. package/dist/utils/defaults.js +322 -0
  156. package/dist/utils/defaults.js.map +1 -0
  157. package/dist/utils/factories.d.ts +144 -0
  158. package/dist/utils/factories.d.ts.map +1 -0
  159. package/dist/utils/factories.js +293 -0
  160. package/dist/utils/factories.js.map +1 -0
  161. package/dist/utils/helpers.d.ts +137 -0
  162. package/dist/utils/helpers.d.ts.map +1 -0
  163. package/dist/utils/helpers.js +221 -0
  164. package/dist/utils/helpers.js.map +1 -0
  165. package/package.json +68 -3
  166. package/src/async/async-queue.ts +417 -0
  167. package/src/async/channels.ts +374 -0
  168. package/src/behaviors/bounded.ts +477 -0
  169. package/src/behaviors/composite.ts +99 -0
  170. package/src/behaviors/evented.ts +464 -0
  171. package/src/behaviors/lru.ts +447 -0
  172. package/src/behaviors/readonly.ts +224 -0
  173. package/src/behaviors/safe.ts +372 -0
  174. package/src/behaviors/synchronized.ts +316 -0
  175. package/src/behaviors/ttl.ts +462 -0
  176. package/src/contracts/model.ts +44 -0
  177. package/src/core/effects.ts +323 -0
  178. package/src/core/events.ts +356 -0
  179. package/src/core/middleware.ts +415 -0
  180. package/src/core/policies.ts +316 -0
  181. package/src/core/traits.ts +164 -0
  182. package/src/fx/collectors.ts +500 -0
  183. package/src/fx/iter.ts +536 -0
  184. package/src/impl/array-deque.ts +463 -0
  185. package/src/impl/array-list.ts +490 -0
  186. package/src/impl/hash-map.ts +623 -0
  187. package/src/impl/hash-set.ts +342 -0
  188. package/src/impl/linked-hash-map.ts +572 -0
  189. package/src/impl/linked-list.ts +606 -0
  190. package/src/impl/priority-queue.ts +448 -0
  191. package/src/impl/tree-map.ts +912 -0
  192. package/src/impl/tree-set.ts +469 -0
  193. package/src/index.ts +277 -0
  194. package/src/interfaces/collection.ts +141 -0
  195. package/src/interfaces/list.ts +281 -0
  196. package/src/interfaces/map.ts +405 -0
  197. package/src/interfaces/queue.ts +353 -0
  198. package/src/interfaces/set.ts +158 -0
  199. package/src/register.ts +8 -0
  200. package/src/storage/index.ts +16 -0
  201. package/src/storage/interface.ts +179 -0
  202. package/src/storage/memory.ts +180 -0
  203. package/src/utils/defaults.ts +345 -0
  204. package/src/utils/factories.ts +357 -0
  205. package/src/utils/helpers.ts +248 -0
@@ -0,0 +1,180 @@
1
+ /**
2
+ * In-Memory Storage Implementation
3
+ *
4
+ * Fast, volatile storage using JavaScript Map.
5
+ * All operations return Promises for interface consistency.
6
+ */
7
+
8
+ import type { CollectionStorage, StorageMetadata } from "./interface.js";
9
+
10
+ /**
11
+ * In-memory storage backed by JavaScript Map.
12
+ *
13
+ * Features:
14
+ * - Fast lookups O(1)
15
+ * - No persistence (data lost on restart)
16
+ * - Memory-bound (limited by available RAM)
17
+ * - Returns Promises for API consistency with remote storage
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const storage = new InMemoryStorage<User>();
22
+ * await storage.set("123", { id: "123", name: "John" });
23
+ * const user = await storage.get("123"); // { id: "123", name: "John" }
24
+ * ```
25
+ */
26
+ export class InMemoryStorage<T> implements CollectionStorage<T> {
27
+ private data = new Map<string, T>();
28
+
29
+ //
30
+ // ═══ Read Operations ═══
31
+ //
32
+
33
+ get(id: string): Promise<T | undefined> {
34
+ return Promise.resolve(this.data.get(id));
35
+ }
36
+
37
+ getAll(): Promise<T[]> {
38
+ return Promise.resolve(Array.from(this.data.values()));
39
+ }
40
+
41
+ find(predicate: (item: T) => boolean): Promise<T[]> {
42
+ const results: T[] = [];
43
+ for (const item of this.data.values()) {
44
+ if (predicate(item)) {
45
+ results.push(item);
46
+ }
47
+ }
48
+ return Promise.resolve(results);
49
+ }
50
+
51
+ has(id: string): Promise<boolean> {
52
+ return Promise.resolve(this.data.has(id));
53
+ }
54
+
55
+ size(): Promise<number> {
56
+ return Promise.resolve(this.data.size);
57
+ }
58
+
59
+ //
60
+ // ═══ Write Operations ═══
61
+ //
62
+
63
+ set(id: string, value: T): Promise<void> {
64
+ this.data.set(id, value);
65
+ return Promise.resolve();
66
+ }
67
+
68
+ delete(id: string): Promise<boolean> {
69
+ return Promise.resolve(this.data.delete(id));
70
+ }
71
+
72
+ clear(): Promise<void> {
73
+ this.data.clear();
74
+ return Promise.resolve();
75
+ }
76
+
77
+ //
78
+ // ═══ Bulk Operations ═══
79
+ //
80
+
81
+ setBatch(items: Array<[string, T]>): Promise<void> {
82
+ for (const [id, value] of items) {
83
+ this.data.set(id, value);
84
+ }
85
+ return Promise.resolve();
86
+ }
87
+
88
+ deleteBatch(ids: string[]): Promise<number> {
89
+ let deleted = 0;
90
+ for (const id of ids) {
91
+ if (this.data.delete(id)) {
92
+ deleted++;
93
+ }
94
+ }
95
+ return Promise.resolve(deleted);
96
+ }
97
+
98
+ getBatch(ids: string[]): Promise<Map<string, T>> {
99
+ const result = new Map<string, T>();
100
+ for (const id of ids) {
101
+ const value = this.data.get(id);
102
+ if (value !== undefined) {
103
+ result.set(id, value);
104
+ }
105
+ }
106
+ return Promise.resolve(result);
107
+ }
108
+
109
+ //
110
+ // ═══ Lifecycle & Metadata ═══
111
+ //
112
+
113
+ close(): Promise<void> {
114
+ // No cleanup needed for in-memory storage
115
+ this.data.clear();
116
+ return Promise.resolve();
117
+ }
118
+
119
+ getMetadata(): Promise<StorageMetadata> {
120
+ // Rough memory estimation:
121
+ // Each entry has ~overhead of 100 bytes (key string + Map entry overhead)
122
+ const estimatedEntrySize = 100;
123
+ const memoryUsage = this.data.size * estimatedEntrySize;
124
+
125
+ return Promise.resolve({
126
+ type: "memory",
127
+ size: this.data.size,
128
+ stats: {
129
+ memoryUsage,
130
+ },
131
+ });
132
+ }
133
+
134
+ //
135
+ // ═══ Additional Methods (Map compatibility) ═══
136
+ //
137
+
138
+ /**
139
+ * Get all keys in storage.
140
+ *
141
+ * @returns Iterator of keys
142
+ */
143
+ keys(): IterableIterator<string> {
144
+ return this.data.keys();
145
+ }
146
+
147
+ /**
148
+ * Get all values in storage.
149
+ *
150
+ * @returns Iterator of values
151
+ */
152
+ values(): IterableIterator<T> {
153
+ return this.data.values();
154
+ }
155
+
156
+ /**
157
+ * Get all entries in storage.
158
+ *
159
+ * @returns Iterator of [id, value] tuples
160
+ */
161
+ entries(): IterableIterator<[string, T]> {
162
+ return this.data.entries();
163
+ }
164
+
165
+ /**
166
+ * Iterate over storage entries.
167
+ *
168
+ * @param callback - Function to call for each entry
169
+ */
170
+ forEach(callback: (value: T, key: string, map: Map<string, T>) => void): void {
171
+ this.data.forEach(callback);
172
+ }
173
+
174
+ /**
175
+ * Make storage iterable.
176
+ */
177
+ [Symbol.iterator](): IterableIterator<[string, T]> {
178
+ return this.data.entries();
179
+ }
180
+ }
@@ -0,0 +1,345 @@
1
+ /**
2
+ * Default implementations of equality, hashing, and comparison functions.
3
+ *
4
+ * Provides sensible defaults for primitive types and utilities for
5
+ * creating custom comparators.
6
+ */
7
+
8
+ import type { Eq, Hash, Compare } from "../core/traits.js";
9
+
10
+ // ============================================================================
11
+ // Default Equality
12
+ // ============================================================================
13
+
14
+ /**
15
+ * Default equality using strict equality (===).
16
+ * Works for primitives and reference equality for objects.
17
+ */
18
+ export const defaultEq: Eq<any> = (a, b) => a === b;
19
+
20
+ /**
21
+ * Structural equality for objects (shallow comparison of properties).
22
+ * Compares own enumerable properties using ===.
23
+ */
24
+ export const shallowEq: Eq<any> = (a, b) => {
25
+ if (a === b) return true;
26
+ if (typeof a !== "object" || typeof b !== "object") return false;
27
+ if (a === null || b === null) return false;
28
+
29
+ const keysA = Object.keys(a);
30
+ const keysB = Object.keys(b);
31
+
32
+ if (keysA.length !== keysB.length) return false;
33
+
34
+ for (const key of keysA) {
35
+ if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
36
+ if (a[key] !== b[key]) return false;
37
+ }
38
+
39
+ return true;
40
+ };
41
+
42
+ /**
43
+ * Deep structural equality (recursive comparison).
44
+ * Handles nested objects and arrays.
45
+ */
46
+ export const deepEq: Eq<any> = (a, b): boolean => {
47
+ if (a === b) return true;
48
+ if (typeof a !== typeof b) return false;
49
+ if (typeof a !== "object" || a === null || b === null) return false;
50
+
51
+ if (Array.isArray(a) && Array.isArray(b)) {
52
+ if (a.length !== b.length) return false;
53
+ for (let i = 0; i < a.length; i++) {
54
+ if (!deepEq(a[i], b[i])) return false;
55
+ }
56
+ return true;
57
+ }
58
+
59
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
60
+
61
+ const keysA = Object.keys(a);
62
+ const keysB = Object.keys(b);
63
+
64
+ if (keysA.length !== keysB.length) return false;
65
+
66
+ for (const key of keysA) {
67
+ if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
68
+ if (!deepEq(a[key], b[key])) return false;
69
+ }
70
+
71
+ return true;
72
+ };
73
+
74
+ /**
75
+ * Equality by comparing a specific property.
76
+ *
77
+ * @example
78
+ * const userEq = eqBy<User, 'id'>('id')
79
+ * // or with accessor function:
80
+ * const userEq = eqBy<User>((u) => u.id)
81
+ */
82
+ export const eqBy = <T, K extends keyof T = keyof T>(
83
+ keyOrFn: K | ((value: T) => any)
84
+ ): Eq<T> => {
85
+ const accessor = typeof keyOrFn === "function" ? keyOrFn : (v: T) => v[keyOrFn];
86
+ return (a, b) => accessor(a) === accessor(b);
87
+ };
88
+
89
+ // ============================================================================
90
+ // Default Hashing
91
+ // ============================================================================
92
+
93
+ /**
94
+ * Default hash function for primitives and objects.
95
+ * For objects, hashes the JSON string representation.
96
+ */
97
+ export const defaultHash: Hash<any> = (value: any): number => {
98
+ if (value === null) return 0;
99
+ if (value === undefined) return 1;
100
+
101
+ const type = typeof value;
102
+
103
+ switch (type) {
104
+ case "boolean":
105
+ return value ? 1 : 0;
106
+ case "number":
107
+ return hashNumber(value);
108
+ case "string":
109
+ return hashString(value);
110
+ case "symbol":
111
+ return hashString(value.toString());
112
+ case "bigint":
113
+ return hashString(value.toString());
114
+ case "object":
115
+ // For objects, hash their JSON representation
116
+ // This is not ideal for all cases but provides a reasonable default
117
+ try {
118
+ return hashString(JSON.stringify(value));
119
+ } catch {
120
+ // If JSON.stringify fails, fall back to toString
121
+ return hashString(value.toString());
122
+ }
123
+ default:
124
+ return 2;
125
+ }
126
+ };
127
+
128
+ /**
129
+ * Hash function for strings using djb2 algorithm.
130
+ */
131
+ export const hashString = (str: string): number => {
132
+ let hash = 5381;
133
+ for (let i = 0; i < str.length; i++) {
134
+ hash = ((hash << 5) + hash) + str.charCodeAt(i); // hash * 33 + c
135
+ hash = hash & hash; // Convert to 32-bit integer
136
+ }
137
+ return hash >>> 0; // Convert to unsigned
138
+ };
139
+
140
+ /**
141
+ * Hash function for numbers.
142
+ */
143
+ export const hashNumber = (num: number): number => {
144
+ if (Number.isNaN(num)) return 0;
145
+ if (!Number.isFinite(num)) return num > 0 ? 1 : -1;
146
+
147
+ // For integers, use the number itself
148
+ if (Number.isInteger(num)) {
149
+ return num | 0; // Convert to 32-bit int
150
+ }
151
+
152
+ // For floats, hash the string representation
153
+ return hashString(num.toString());
154
+ };
155
+
156
+ /**
157
+ * Combine multiple hash values.
158
+ * Useful for hashing objects with multiple fields.
159
+ *
160
+ * @example
161
+ * const pointHash: Hash<Point> = (p) =>
162
+ * combineHashes(hashNumber(p.x), hashNumber(p.y))
163
+ */
164
+ export const combineHashes = (...hashes: number[]): number => {
165
+ let combined = 0;
166
+ for (const hash of hashes) {
167
+ combined = ((combined << 5) - combined) + hash;
168
+ combined = combined & combined; // Convert to 32-bit int
169
+ }
170
+ return combined >>> 0; // Convert to unsigned
171
+ };
172
+
173
+ /**
174
+ * Create a hash function that hashes by a specific property.
175
+ *
176
+ * @example
177
+ * const userHash = hashBy<User>((u) => u.id)
178
+ */
179
+ export const hashBy = <T>(accessor: (value: T) => any): Hash<T> => {
180
+ return (value) => defaultHash(accessor(value));
181
+ };
182
+
183
+ // ============================================================================
184
+ // Default Comparison
185
+ // ============================================================================
186
+
187
+ /**
188
+ * Natural ordering comparison for primitives.
189
+ * Numbers, strings, booleans, dates are compared naturally.
190
+ */
191
+ export const defaultCompare: Compare<any> = (a, b) => {
192
+ if (a === b) return 0;
193
+ if (a === null || a === undefined) return -1;
194
+ if (b === null || b === undefined) return 1;
195
+
196
+ // Handle dates
197
+ if (a instanceof Date && b instanceof Date) {
198
+ return a.getTime() - b.getTime();
199
+ }
200
+
201
+ // Handle numbers
202
+ if (typeof a === "number" && typeof b === "number") {
203
+ if (Number.isNaN(a)) return Number.isNaN(b) ? 0 : -1;
204
+ if (Number.isNaN(b)) return 1;
205
+ return a - b;
206
+ }
207
+
208
+ // Handle strings
209
+ if (typeof a === "string" && typeof b === "string") {
210
+ return a.localeCompare(b);
211
+ }
212
+
213
+ // Handle booleans
214
+ if (typeof a === "boolean" && typeof b === "boolean") {
215
+ return a === b ? 0 : a ? 1 : -1;
216
+ }
217
+
218
+ // Fallback: convert to string and compare
219
+ return String(a).localeCompare(String(b));
220
+ };
221
+
222
+ /**
223
+ * Numeric comparison (for numbers).
224
+ */
225
+ export const numberCompare: Compare<number> = (a, b) => {
226
+ if (Number.isNaN(a)) return Number.isNaN(b) ? 0 : -1;
227
+ if (Number.isNaN(b)) return 1;
228
+ return a - b;
229
+ };
230
+
231
+ /**
232
+ * String comparison using locale-aware sorting.
233
+ */
234
+ export const stringCompare: Compare<string> = (a, b) => a.localeCompare(b);
235
+
236
+ /**
237
+ * Case-insensitive string comparison.
238
+ */
239
+ export const stringCompareIgnoreCase: Compare<string> = (a, b) =>
240
+ a.toLowerCase().localeCompare(b.toLowerCase());
241
+
242
+ /**
243
+ * Date comparison.
244
+ */
245
+ export const dateCompare: Compare<Date> = (a, b) =>
246
+ a.getTime() - b.getTime();
247
+
248
+ /**
249
+ * Boolean comparison (false < true).
250
+ */
251
+ export const booleanCompare: Compare<boolean> = (a, b) =>
252
+ a === b ? 0 : a ? 1 : -1;
253
+
254
+ // ============================================================================
255
+ // Comparator Combinators
256
+ // ============================================================================
257
+
258
+ /**
259
+ * Reverses a comparator.
260
+ *
261
+ * @example
262
+ * const descending = reversed(numberCompare)
263
+ */
264
+ export const reversed = <T>(compare: Compare<T>): Compare<T> =>
265
+ (a, b) => compare(b, a);
266
+
267
+ /**
268
+ * Creates a comparator that compares by a specific property or function.
269
+ *
270
+ * @example
271
+ * const byAge = comparing<Person>((p) => p.age)
272
+ * const byName = comparing<Person, 'name'>('name')
273
+ */
274
+ export const comparing = <T, K extends keyof T = keyof T>(
275
+ keyOrFn: K | ((value: T) => any),
276
+ compare: Compare<any> = defaultCompare
277
+ ): Compare<T> => {
278
+ const accessor = typeof keyOrFn === "function" ? keyOrFn : (v: T) => v[keyOrFn];
279
+ return (a, b) => compare(accessor(a), accessor(b));
280
+ };
281
+
282
+ /**
283
+ * Chains comparators. If the first comparator returns 0 (equal),
284
+ * tries the next comparator, and so on.
285
+ *
286
+ * @example
287
+ * const userCompare = thenComparing(
288
+ * comparing<User>('lastName'),
289
+ * comparing<User>('firstName'),
290
+ * comparing<User>('age')
291
+ * )
292
+ */
293
+ export const thenComparing = <T>(...comparators: Compare<T>[]): Compare<T> => {
294
+ return (a, b) => {
295
+ for (const compare of comparators) {
296
+ const result = compare(a, b);
297
+ if (result !== 0) return result;
298
+ }
299
+ return 0;
300
+ };
301
+ };
302
+
303
+ /**
304
+ * Creates a comparator that treats null/undefined as less than all other values.
305
+ *
306
+ * @example
307
+ * const compare = nullsFirst(numberCompare)
308
+ */
309
+ export const nullsFirst = <T>(compare: Compare<T>): Compare<T | null | undefined> => {
310
+ return (a, b) => {
311
+ if (a == null && b == null) return 0;
312
+ if (a == null) return -1;
313
+ if (b == null) return 1;
314
+ return compare(a, b);
315
+ };
316
+ };
317
+
318
+ /**
319
+ * Creates a comparator that treats null/undefined as greater than all other values.
320
+ *
321
+ * @example
322
+ * const compare = nullsLast(numberCompare)
323
+ */
324
+ export const nullsLast = <T>(compare: Compare<T>): Compare<T | null | undefined> => {
325
+ return (a, b) => {
326
+ if (a == null && b == null) return 0;
327
+ if (a == null) return 1;
328
+ if (b == null) return -1;
329
+ return compare(a, b);
330
+ };
331
+ };
332
+
333
+ /**
334
+ * Creates a comparator from a key extraction function.
335
+ * Elements are compared by their extracted keys.
336
+ *
337
+ * @example
338
+ * const byLength = comparingKey<string>((s) => s.length)
339
+ */
340
+ export const comparingKey = <T, K>(
341
+ keyExtractor: (value: T) => K,
342
+ keyCompare: Compare<K> = defaultCompare
343
+ ): Compare<T> => {
344
+ return (a, b) => keyCompare(keyExtractor(a), keyExtractor(b));
345
+ };