@mark1russell7/collections 0.0.0-bootstrap.0 → 0.1.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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +77 -1
  3. package/build/dag/index.d.ts +144 -0
  4. package/build/dag/index.d.ts.map +1 -0
  5. package/build/dag/index.js +294 -0
  6. package/build/dag/index.js.map +1 -0
  7. package/build/graph/index.d.ts +20 -0
  8. package/build/graph/index.d.ts.map +1 -0
  9. package/build/graph/index.js +48 -0
  10. package/build/graph/index.js.map +1 -0
  11. package/build/index.d.ts +4952 -0
  12. package/build/index.d.ts.map +1 -0
  13. package/build/index.js +7811 -0
  14. package/build/index.js.map +1 -0
  15. package/build/testing/index.d.ts +25 -0
  16. package/build/testing/index.d.ts.map +1 -0
  17. package/build/testing/index.js +72 -0
  18. package/build/testing/index.js.map +1 -0
  19. package/package.json +71 -4
  20. package/src/async/async-queue.ts +481 -0
  21. package/src/async/channels.ts +450 -0
  22. package/src/async/settled.ts +41 -0
  23. package/src/behaviors/bounded.ts +485 -0
  24. package/src/behaviors/composite.ts +99 -0
  25. package/src/behaviors/evented.ts +464 -0
  26. package/src/behaviors/lru.ts +449 -0
  27. package/src/behaviors/readonly.ts +236 -0
  28. package/src/behaviors/safe.ts +358 -0
  29. package/src/behaviors/synchronized.ts +316 -0
  30. package/src/behaviors/ttl.ts +464 -0
  31. package/src/core/effects.ts +327 -0
  32. package/src/core/events.ts +363 -0
  33. package/src/core/middleware.ts +413 -0
  34. package/src/core/policies.ts +316 -0
  35. package/src/core/traits.ts +164 -0
  36. package/src/dag/builder.ts +124 -0
  37. package/src/dag/executor.ts +190 -0
  38. package/src/dag/index.ts +14 -0
  39. package/src/dag/traversal.ts +129 -0
  40. package/src/dag/types.ts +87 -0
  41. package/src/fx/collectors.ts +500 -0
  42. package/src/fx/iter.ts +536 -0
  43. package/src/graph/hub-order.ts +53 -0
  44. package/src/graph/index.ts +5 -0
  45. package/src/impl/array-deque.ts +463 -0
  46. package/src/impl/array-list.ts +490 -0
  47. package/src/impl/hash-map.ts +623 -0
  48. package/src/impl/hash-set.ts +342 -0
  49. package/src/impl/linked-hash-map.ts +572 -0
  50. package/src/impl/linked-list.ts +610 -0
  51. package/src/impl/priority-queue.ts +448 -0
  52. package/src/impl/summary-tree.ts +594 -0
  53. package/src/impl/tree-map.ts +913 -0
  54. package/src/impl/tree-set.ts +469 -0
  55. package/src/index.ts +237 -0
  56. package/src/interfaces/collection.ts +141 -0
  57. package/src/interfaces/list.ts +281 -0
  58. package/src/interfaces/map.ts +405 -0
  59. package/src/interfaces/queue.ts +353 -0
  60. package/src/interfaces/set.ts +158 -0
  61. package/src/order/index.ts +6 -0
  62. package/src/order/rank.ts +271 -0
  63. package/src/storage/listeners.ts +72 -0
  64. package/src/testing/check.ts +81 -0
  65. package/src/testing/index.ts +7 -0
  66. package/src/utils/defaults.ts +345 -0
  67. package/src/utils/factories.ts +357 -0
  68. package/src/utils/helpers.ts +248 -0
@@ -0,0 +1,345 @@
1
+ /**
2
+ * Default implementations of equality, hashing, and comparison functions.
3
+ *
4
+ * This module gives sensible defaults for primitive types and utilities for
5
+ * making 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
+ * This function 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
+ * This function 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
+ * Make 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
+ * This function 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
+ * This function makes 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 gives 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
+ * This function makes 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
+ * This function makes 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
+ * This function makes 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
+ };
@@ -0,0 +1,357 @@
1
+ /**
2
+ * Factory utilities for making collections.
3
+ *
4
+ * This module gives convenient factory methods similar to Java's Collections class.
5
+ * These functions mirror Java methods like Collections.emptyList() and singletonList().
6
+ */
7
+
8
+ import { arrayList, ArrayList } from "../impl/array-list.js";
9
+ import { arrayDeque, ArrayDeque } from "../impl/array-deque.js";
10
+ import { hashMap, HashMap } from "../impl/hash-map.js";
11
+ import type { List } from "../interfaces/list.js";
12
+ import type { Queue } from "../interfaces/queue.js";
13
+ import type { MapLike } from "../interfaces/map.js";
14
+ import { readonly } from "../behaviors/readonly.js";
15
+ import { compose } from "../core/middleware.js";
16
+
17
+ // ============================================================================
18
+ // Empty collections
19
+ // ============================================================================
20
+
21
+ /**
22
+ * This value is an empty, immutable list.
23
+ * Multiple calls return the same instance (singleton pattern).
24
+ *
25
+ * @example
26
+ * const list = emptyList<number>()
27
+ * list.size // 0
28
+ * list.add(1) // Error: Cannot modify readonly collection
29
+ */
30
+ const EMPTY_LIST_CACHE = new Map<any, any>();
31
+
32
+ export function emptyList<T>(): List<T> {
33
+ const key = "list";
34
+ if (!EMPTY_LIST_CACHE.has(key)) {
35
+ const list = compose(readonly<List<T>>())(arrayList<T>());
36
+ EMPTY_LIST_CACHE.set(key, list);
37
+ }
38
+ return EMPTY_LIST_CACHE.get(key);
39
+ }
40
+
41
+ /**
42
+ * This value is an empty, immutable queue.
43
+ */
44
+ const EMPTY_QUEUE_CACHE = new Map<any, any>();
45
+
46
+ export function emptyQueue<T>(): Queue<T> {
47
+ const key = "queue";
48
+ if (!EMPTY_QUEUE_CACHE.has(key)) {
49
+ const queue = compose(readonly<Queue<T>>())(arrayDeque<T>() as Queue<T>);
50
+ EMPTY_QUEUE_CACHE.set(key, queue);
51
+ }
52
+ return EMPTY_QUEUE_CACHE.get(key);
53
+ }
54
+
55
+ /**
56
+ * This value is an empty, immutable map.
57
+ */
58
+ const EMPTY_MAP_CACHE = new Map<any, any>();
59
+
60
+ export function emptyMap<K, V>(): MapLike<K, V> {
61
+ const key = "map";
62
+ if (!EMPTY_MAP_CACHE.has(key)) {
63
+ const map = compose(readonly<MapLike<K, V>>())(hashMap<K, V>());
64
+ EMPTY_MAP_CACHE.set(key, map);
65
+ }
66
+ return EMPTY_MAP_CACHE.get(key);
67
+ }
68
+
69
+ // ============================================================================
70
+ // Singleton collections (single element)
71
+ // ============================================================================
72
+
73
+ /**
74
+ * This function gives an immutable list containing only the specified element.
75
+ *
76
+ * @example
77
+ * const list = singletonList(42)
78
+ * list.size // 1
79
+ * list.get(0) // 42
80
+ * list.add(2) // Error: Cannot modify readonly collection
81
+ */
82
+ export function singletonList<T>(element: T): List<T> {
83
+ const list = arrayList<T>();
84
+ list.add(element);
85
+ return compose(readonly<List<T>>())(list);
86
+ }
87
+
88
+ /**
89
+ * This function gives an immutable map containing only the specified key-value mapping.
90
+ */
91
+ export function singletonMap<K, V>(key: K, value: V): MapLike<K, V> {
92
+ const map = hashMap<K, V>();
93
+ map.set(key, value);
94
+ return compose(readonly<MapLike<K, V>>())(map);
95
+ }
96
+
97
+ // ============================================================================
98
+ // N-copies collections
99
+ // ============================================================================
100
+
101
+ /**
102
+ * This function gives an immutable list consisting of n copies of the specified element.
103
+ *
104
+ * @example
105
+ * const list = nCopies(5, 'hello')
106
+ * list.size // 5
107
+ * list.get(2) // 'hello'
108
+ */
109
+ export function nCopies<T>(n: number, element: T): List<T> {
110
+ if (n < 0) {
111
+ throw new Error(`n must be non-negative, got ${n}`);
112
+ }
113
+
114
+ const list = arrayList<T>();
115
+ for (let i = 0; i < n; i++) {
116
+ list.add(element);
117
+ }
118
+ return compose(readonly<List<T>>())(list);
119
+ }
120
+
121
+ // ============================================================================
122
+ // Collection creation from iterables
123
+ // ============================================================================
124
+
125
+ /**
126
+ * This function makes a new ArrayList from the given elements.
127
+ *
128
+ * @example
129
+ * const list = listOf(1, 2, 3, 4, 5)
130
+ */
131
+ export function listOf<T>(...elements: T[]): ArrayList<T> {
132
+ return arrayList(elements);
133
+ }
134
+
135
+ /**
136
+ * This function makes a new ArrayDeque from the given elements.
137
+ */
138
+ export function queueOf<T>(...elements: T[]): ArrayDeque<T> {
139
+ return arrayDeque(elements);
140
+ }
141
+
142
+ /**
143
+ * This function makes a new HashMap from the given key-value pairs.
144
+ *
145
+ * @example
146
+ * const map = mapOf(['a', 1], ['b', 2], ['c', 3])
147
+ */
148
+ export function mapOf<K, V>(...entries: [K, V][]): HashMap<K, V> {
149
+ return hashMap(entries);
150
+ }
151
+
152
+ // ============================================================================
153
+ // Mutable collection factories
154
+ // ============================================================================
155
+
156
+ /**
157
+ * This function makes a new mutable ArrayList with optional initial elements.
158
+ *
159
+ * @example
160
+ * const list = mutableListOf(1, 2, 3)
161
+ * list.add(4)
162
+ */
163
+ export function mutableListOf<T>(...elements: T[]): ArrayList<T> {
164
+ return arrayList(elements);
165
+ }
166
+
167
+ /**
168
+ * This function makes a new mutable HashMap with optional initial entries.
169
+ */
170
+ export function mutableMapOf<K, V>(...entries: [K, V][]): HashMap<K, V> {
171
+ return hashMap(entries);
172
+ }
173
+
174
+ // ============================================================================
175
+ // Immutable collection factories
176
+ // ============================================================================
177
+
178
+ /**
179
+ * This function makes an immutable List from the given elements.
180
+ *
181
+ * @example
182
+ * const list = immutableListOf(1, 2, 3)
183
+ * list.get(0) // 1
184
+ * list.add(4) // Error: Cannot modify readonly collection
185
+ */
186
+ export function immutableListOf<T>(...elements: T[]): List<T> {
187
+ if (elements.length === 0) {
188
+ return emptyList<T>();
189
+ }
190
+ if (elements.length === 1) {
191
+ return singletonList(elements[0]! as T);
192
+ }
193
+ const list = arrayList(elements);
194
+ return compose(readonly<List<T>>())(list);
195
+ }
196
+
197
+ /**
198
+ * This function makes an immutable Map from the given entries.
199
+ */
200
+ export function immutableMapOf<K, V>(...entries: [K, V][]): MapLike<K, V> {
201
+ if (entries.length === 0) {
202
+ return emptyMap<K, V>();
203
+ }
204
+ if (entries.length === 1) {
205
+ return singletonMap(entries[0]![0], entries[0]![1]);
206
+ }
207
+ const map = hashMap(entries);
208
+ return compose(readonly<MapLike<K, V>>())(map);
209
+ }
210
+
211
+ // ============================================================================
212
+ // Range factories
213
+ // ============================================================================
214
+
215
+ /**
216
+ * This function makes a list containing integers from start (inclusive) to end (exclusive).
217
+ *
218
+ * @example
219
+ * const list = range(0, 5) // [0, 1, 2, 3, 4]
220
+ * const list2 = range(10, 15) // [10, 11, 12, 13, 14]
221
+ */
222
+ export function range(start: number, end: number, step: number = 1): ArrayList<number> {
223
+ if (step === 0) {
224
+ throw new Error("step cannot be zero");
225
+ }
226
+
227
+ const list = arrayList<number>();
228
+
229
+ if (step > 0) {
230
+ for (let i = start; i < end; i += step) {
231
+ list.add(i);
232
+ }
233
+ } else {
234
+ for (let i = start; i > end; i += step) {
235
+ list.add(i);
236
+ }
237
+ }
238
+
239
+ return list;
240
+ }
241
+
242
+ /**
243
+ * This function makes a list containing integers from 0 to n (exclusive).
244
+ *
245
+ * @example
246
+ * const list = rangeTo(5) // [0, 1, 2, 3, 4]
247
+ */
248
+ export function rangeTo(n: number): ArrayList<number> {
249
+ return range(0, n);
250
+ }
251
+
252
+ // ============================================================================
253
+ // Collection builders
254
+ // ============================================================================
255
+
256
+ /**
257
+ * Builder for constructing lists with a fluent API.
258
+ *
259
+ * @example
260
+ * const list = buildList<number>((builder) => {
261
+ * builder.add(1)
262
+ * builder.add(2)
263
+ * if (someCondition) {
264
+ * builder.add(3)
265
+ * }
266
+ * })
267
+ */
268
+ export function buildList<T>(builder: (list: ArrayList<T>) => void): ArrayList<T> {
269
+ const list = arrayList<T>();
270
+ builder(list);
271
+ return list;
272
+ }
273
+
274
+ /**
275
+ * Builder for constructing maps with a fluent API.
276
+ */
277
+ export function buildMap<K, V>(builder: (map: HashMap<K, V>) => void): HashMap<K, V> {
278
+ const map = hashMap<K, V>();
279
+ builder(map);
280
+ return map;
281
+ }
282
+
283
+ // ============================================================================
284
+ // Conversion utilities
285
+ // ============================================================================
286
+
287
+ /**
288
+ * This function converts an iterable to an ArrayList.
289
+ *
290
+ * @example
291
+ * const set = new Set([1, 2, 3])
292
+ * const list = toList(set)
293
+ */
294
+ export function toList<T>(iterable: Iterable<T>): ArrayList<T> {
295
+ return arrayList(iterable);
296
+ }
297
+
298
+ /**
299
+ * This function converts an iterable to a HashMap using a key extractor function.
300
+ *
301
+ * @example
302
+ * const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
303
+ * const userMap = toMap(users, u => u.id)
304
+ */
305
+ export function toMap<T, K>(
306
+ iterable: Iterable<T>,
307
+ keyExtractor: (value: T) => K
308
+ ): HashMap<K, T>;
309
+ export function toMap<T, K, V>(
310
+ iterable: Iterable<T>,
311
+ keyExtractor: (value: T) => K,
312
+ valueExtractor: (value: T) => V
313
+ ): HashMap<K, V>;
314
+ export function toMap<T, K, V>(
315
+ iterable: Iterable<T>,
316
+ keyExtractor: (value: T) => K,
317
+ valueExtractor?: (value: T) => V
318
+ ): HashMap<K, any> {
319
+ const map = hashMap<K, any>();
320
+ for (const item of iterable) {
321
+ const key = keyExtractor(item);
322
+ const value = valueExtractor ? valueExtractor(item) : item;
323
+ map.set(key, value);
324
+ }
325
+ return map;
326
+ }
327
+
328
+ // ============================================================================
329
+ // Grouping utilities
330
+ // ============================================================================
331
+
332
+ /**
333
+ * This function groups elements by a key extractor function.
334
+ *
335
+ * @example
336
+ * const users = [
337
+ * { age: 25, name: 'Alice' },
338
+ * { age: 30, name: 'Bob' },
339
+ * { age: 25, name: 'Charlie' }
340
+ * ]
341
+ * const byAge = groupBy(users, u => u.age)
342
+ * // Map { 25 => [Alice, Charlie], 30 => [Bob] }
343
+ */
344
+ export function groupBy<T, K>(
345
+ iterable: Iterable<T>,
346
+ keyExtractor: (value: T) => K
347
+ ): HashMap<K, ArrayList<T>> {
348
+ const map = hashMap<K, ArrayList<T>>();
349
+
350
+ for (const item of iterable) {
351
+ const key = keyExtractor(item);
352
+ const list = map.computeIfAbsent(key, () => arrayList<T>());
353
+ list.add(item);
354
+ }
355
+
356
+ return map;
357
+ }