data-structure-typed 2.0.1 → 2.0.2

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 (45) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/dist/cjs/data-structures/binary-tree/binary-tree.js +8 -9
  3. package/dist/cjs/data-structures/binary-tree/binary-tree.js.map +1 -1
  4. package/dist/cjs/types/utils/utils.d.ts +1 -7
  5. package/dist/cjs/utils/utils.d.ts +3 -49
  6. package/dist/cjs/utils/utils.js +13 -82
  7. package/dist/cjs/utils/utils.js.map +1 -1
  8. package/dist/esm/data-structures/binary-tree/binary-tree.js +8 -9
  9. package/dist/esm/data-structures/binary-tree/binary-tree.js.map +1 -1
  10. package/dist/esm/types/utils/utils.d.ts +1 -7
  11. package/dist/esm/utils/utils.d.ts +3 -49
  12. package/dist/esm/utils/utils.js +10 -68
  13. package/dist/esm/utils/utils.js.map +1 -1
  14. package/dist/umd/data-structure-typed.js +18 -66
  15. package/dist/umd/data-structure-typed.min.js +2 -2
  16. package/dist/umd/data-structure-typed.min.js.map +1 -1
  17. package/package.json +1 -1
  18. package/src/data-structures/binary-tree/binary-tree.ts +9 -10
  19. package/src/types/utils/utils.ts +1 -6
  20. package/src/utils/utils.ts +11 -83
  21. package/test/unit/data-structures/queue/queue.test.ts +1 -1
  22. package/test/unit/utils/utils.test.ts +35 -2
  23. package/dist/individuals/binary-tree/avl-tree-counter.mjs +0 -4701
  24. package/dist/individuals/binary-tree/avl-tree-multi-map.mjs +0 -4514
  25. package/dist/individuals/binary-tree/avl-tree.mjs +0 -4321
  26. package/dist/individuals/binary-tree/binary-tree.mjs +0 -3097
  27. package/dist/individuals/binary-tree/bst.mjs +0 -3858
  28. package/dist/individuals/binary-tree/red-black-tree.mjs +0 -4391
  29. package/dist/individuals/binary-tree/tree-counter.mjs +0 -4806
  30. package/dist/individuals/binary-tree/tree-multi-map.mjs +0 -4582
  31. package/dist/individuals/graph/directed-graph.mjs +0 -2910
  32. package/dist/individuals/graph/undirected-graph.mjs +0 -2745
  33. package/dist/individuals/hash/hash-map.mjs +0 -1040
  34. package/dist/individuals/heap/heap.mjs +0 -909
  35. package/dist/individuals/heap/max-heap.mjs +0 -671
  36. package/dist/individuals/heap/min-heap.mjs +0 -659
  37. package/dist/individuals/linked-list/doubly-linked-list.mjs +0 -1495
  38. package/dist/individuals/linked-list/singly-linked-list.mjs +0 -1479
  39. package/dist/individuals/priority-queue/max-priority-queue.mjs +0 -768
  40. package/dist/individuals/priority-queue/min-priority-queue.mjs +0 -757
  41. package/dist/individuals/priority-queue/priority-queue.mjs +0 -670
  42. package/dist/individuals/queue/deque.mjs +0 -1262
  43. package/dist/individuals/queue/queue.mjs +0 -1865
  44. package/dist/individuals/stack/stack.mjs +0 -415
  45. package/dist/individuals/trie/trie.mjs +0 -687
@@ -1,2910 +0,0 @@
1
- // src/utils/utils.ts
2
- var uuidV4 = function() {
3
- return "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".replace(/[x]/g, function(c) {
4
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
5
- return v.toString(16);
6
- });
7
- };
8
- var arrayRemove = function(array, predicate) {
9
- let i = -1, len = array ? array.length : 0;
10
- const result = [];
11
- while (++i < len) {
12
- const value = array[i];
13
- if (predicate(value, i, array)) {
14
- result.push(value);
15
- Array.prototype.splice.call(array, i--, 1);
16
- len--;
17
- }
18
- }
19
- return result;
20
- };
21
- var THUNK_SYMBOL = Symbol("thunk");
22
-
23
- // src/data-structures/base/iterable-entry-base.ts
24
- var IterableEntryBase = class {
25
- /**
26
- * Time Complexity: O(n)
27
- * Space Complexity: O(1)
28
- *
29
- * The function is an implementation of the Symbol.iterator method that returns an iterable iterator.
30
- * @param {any[]} args - The `args` parameter in the code snippet represents a rest parameter. It
31
- * allows the function to accept any number of arguments as an array. In this case, the `args`
32
- * parameter is used to pass any additional arguments to the `_getIterator` method.
33
- */
34
- *[Symbol.iterator](...args) {
35
- yield* this._getIterator(...args);
36
- }
37
- /**
38
- * Time Complexity: O(n)
39
- * Space Complexity: O(n)
40
- *
41
- * The function returns an iterator that yields key-value pairs from the object, where the value can
42
- * be undefined.
43
- */
44
- *entries() {
45
- for (const item of this) {
46
- yield item;
47
- }
48
- }
49
- /**
50
- * Time Complexity: O(n)
51
- * Space Complexity: O(n)
52
- *
53
- * The function returns an iterator that yields the keys of a data structure.
54
- */
55
- *keys() {
56
- for (const item of this) {
57
- yield item[0];
58
- }
59
- }
60
- /**
61
- * Time Complexity: O(n)
62
- * Space Complexity: O(n)
63
- *
64
- * The function returns an iterator that yields the values of a collection.
65
- */
66
- *values() {
67
- for (const item of this) {
68
- yield item[1];
69
- }
70
- }
71
- /**
72
- * Time Complexity: O(n)
73
- * Space Complexity: O(1)
74
- *
75
- * The `every` function checks if every element in a collection satisfies a given condition.
76
- * @param predicate - The `predicate` parameter is a callback function that takes three arguments:
77
- * `value`, `key`, and `index`. It should return a boolean value indicating whether the condition is
78
- * met for the current element in the iteration.
79
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that specifies the value
80
- * to be used as `this` when executing the `predicate` function. If `thisArg` is provided, it will be
81
- * passed as the first argument to the `predicate` function. If `thisArg` is not provided
82
- * @returns The `every` method is returning a boolean value. It returns `true` if every element in
83
- * the collection satisfies the provided predicate function, and `false` otherwise.
84
- */
85
- every(predicate, thisArg) {
86
- let index = 0;
87
- for (const item of this) {
88
- if (!predicate.call(thisArg, item[0], item[1], index++, this)) {
89
- return false;
90
- }
91
- }
92
- return true;
93
- }
94
- /**
95
- * Time Complexity: O(n)
96
- * Space Complexity: O(1)
97
- *
98
- * The "some" function iterates over a collection and returns true if at least one element satisfies
99
- * a given predicate.
100
- * @param predicate - The `predicate` parameter is a callback function that takes three arguments:
101
- * `value`, `key`, and `index`. It should return a boolean value indicating whether the condition is
102
- * met for the current element in the iteration.
103
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that specifies the value
104
- * to be used as the `this` value when executing the `predicate` function. If `thisArg` is provided,
105
- * it will be passed as the first argument to the `predicate` function. If `thisArg` is
106
- * @returns a boolean value. It returns true if the predicate function returns true for any pair in
107
- * the collection, and false otherwise.
108
- */
109
- some(predicate, thisArg) {
110
- let index = 0;
111
- for (const item of this) {
112
- if (predicate.call(thisArg, item[0], item[1], index++, this)) {
113
- return true;
114
- }
115
- }
116
- return false;
117
- }
118
- /**
119
- * Time Complexity: O(n)
120
- * Space Complexity: O(1)
121
- *
122
- * The `forEach` function iterates over each key-value pair in a collection and executes a callback
123
- * function for each pair.
124
- * @param callbackfn - The callback function that will be called for each element in the collection.
125
- * It takes four parameters: the value of the current element, the key of the current element, the
126
- * index of the current element, and the collection itself.
127
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that allows you to
128
- * specify the value of `this` within the callback function. If `thisArg` is provided, it will be
129
- * used as the `this` value when calling the callback function. If `thisArg` is not provided, `
130
- */
131
- forEach(callbackfn, thisArg) {
132
- let index = 0;
133
- for (const item of this) {
134
- const [key, value] = item;
135
- callbackfn.call(thisArg, key, value, index++, this);
136
- }
137
- }
138
- /**
139
- * Time Complexity: O(n)
140
- * Space Complexity: O(1)
141
- *
142
- * The `find` function iterates over the entries of a collection and returns the first value for
143
- * which the callback function returns true.
144
- * @param callbackfn - The callback function that will be called for each entry in the collection. It
145
- * takes three arguments: the value of the entry, the key of the entry, and the index of the entry in
146
- * the collection. It should return a boolean value indicating whether the current entry matches the
147
- * desired condition.
148
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that specifies the value
149
- * to be used as `this` when executing the `callbackfn` function. If `thisArg` is provided, it will
150
- * be passed as the `this` value to the `callbackfn` function. If `thisArg
151
- * @returns The method `find` returns the value of the first element in the iterable that satisfies
152
- * the provided callback function. If no element satisfies the callback function, `undefined` is
153
- * returned.
154
- */
155
- find(callbackfn, thisArg) {
156
- let index = 0;
157
- for (const item of this) {
158
- const [key, value] = item;
159
- if (callbackfn.call(thisArg, key, value, index++, this)) return item;
160
- }
161
- return;
162
- }
163
- /**
164
- * Time Complexity: O(n)
165
- * Space Complexity: O(1)
166
- *
167
- * The function checks if a given key exists in a collection.
168
- * @param {K} key - The parameter "key" is of type K, which means it can be any type. It represents
169
- * the key that we want to check for existence in the data structure.
170
- * @returns a boolean value. It returns true if the key is found in the collection, and false
171
- * otherwise.
172
- */
173
- has(key) {
174
- for (const item of this) {
175
- const [itemKey] = item;
176
- if (itemKey === key) return true;
177
- }
178
- return false;
179
- }
180
- /**
181
- * Time Complexity: O(n)
182
- * Space Complexity: O(1)
183
- *
184
- * The function checks if a given value exists in a collection.
185
- * @param {V} value - The parameter "value" is the value that we want to check if it exists in the
186
- * collection.
187
- * @returns a boolean value, either true or false.
188
- */
189
- hasValue(value) {
190
- for (const [, elementValue] of this) {
191
- if (elementValue === value) return true;
192
- }
193
- return false;
194
- }
195
- /**
196
- * Time Complexity: O(n)
197
- * Space Complexity: O(1)
198
- *
199
- * The `get` function retrieves the value associated with a given key from a collection.
200
- * @param {K} key - K (the type of the key) - This parameter represents the key that is being
201
- * searched for in the collection.
202
- * @returns The `get` method returns the value associated with the specified key if it exists in the
203
- * collection, otherwise it returns `undefined`.
204
- */
205
- get(key) {
206
- for (const item of this) {
207
- const [itemKey, value] = item;
208
- if (itemKey === key) return value;
209
- }
210
- return;
211
- }
212
- /**
213
- * Time Complexity: O(n)
214
- * Space Complexity: O(1)
215
- *
216
- * The `reduce` function iterates over key-value pairs and applies a callback function to each pair,
217
- * accumulating a single value.
218
- * @param callbackfn - The callback function that will be called for each element in the collection.
219
- * It takes four arguments: the current accumulator value, the current value of the element, the key
220
- * of the element, and the index of the element in the collection. It should return the updated
221
- * accumulator value.
222
- * @param {U} initialValue - The `initialValue` parameter is the initial value of the accumulator. It
223
- * is the value that will be used as the first argument to the `callbackfn` function when reducing
224
- * the elements of the collection.
225
- * @returns The `reduce` method is returning the final value of the accumulator after iterating over
226
- * all the elements in the collection.
227
- */
228
- reduce(callbackfn, initialValue) {
229
- let accumulator = initialValue;
230
- let index = 0;
231
- for (const item of this) {
232
- const [key, value] = item;
233
- accumulator = callbackfn(accumulator, value, key, index++, this);
234
- }
235
- return accumulator;
236
- }
237
- /**
238
- * Time Complexity: O(n)
239
- * Space Complexity: O(n)
240
- *
241
- * The print function logs the elements of an array to the console.
242
- */
243
- toVisual() {
244
- return [...this];
245
- }
246
- /**
247
- * Time Complexity: O(n)
248
- * Space Complexity: O(n)
249
- *
250
- * The print function logs the elements of an array to the console.
251
- */
252
- print() {
253
- console.log(this.toVisual());
254
- }
255
- };
256
-
257
- // src/data-structures/base/iterable-element-base.ts
258
- var IterableElementBase = class {
259
- /**
260
- * The protected constructor initializes the options for the IterableElementBase class, including the
261
- * toElementFn function.
262
- * @param [options] - An optional object that contains the following properties:
263
- */
264
- constructor(options) {
265
- if (options) {
266
- const { toElementFn } = options;
267
- if (typeof toElementFn === "function") this._toElementFn = toElementFn;
268
- else if (toElementFn) throw new TypeError("toElementFn must be a function type");
269
- }
270
- }
271
- _toElementFn;
272
- get toElementFn() {
273
- return this._toElementFn;
274
- }
275
- /**
276
- * Time Complexity: O(n)
277
- * Space Complexity: O(1)
278
- *
279
- * The function is an implementation of the Symbol.iterator method that returns an IterableIterator.
280
- * @param {any[]} args - The `args` parameter in the code snippet represents a rest parameter. It
281
- * allows the function to accept any number of arguments as an array. In this case, the `args`
282
- * parameter is used to pass any number of arguments to the `_getIterator` method.
283
- */
284
- *[Symbol.iterator](...args) {
285
- yield* this._getIterator(...args);
286
- }
287
- /**
288
- * Time Complexity: O(n)
289
- * Space Complexity: O(n)
290
- *
291
- * The function returns an iterator that yields all the values in the object.
292
- */
293
- *values() {
294
- for (const item of this) {
295
- yield item;
296
- }
297
- }
298
- /**
299
- * Time Complexity: O(n)
300
- * Space Complexity: O(1)
301
- *
302
- * The `every` function checks if every element in the array satisfies a given predicate.
303
- * @param predicate - The `predicate` parameter is a callback function that takes three arguments:
304
- * the current element being processed, its index, and the array it belongs to. It should return a
305
- * boolean value indicating whether the element satisfies a certain condition or not.
306
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that specifies the value
307
- * to be used as `this` when executing the `predicate` function. If `thisArg` is provided, it will be
308
- * passed as the `this` value to the `predicate` function. If `thisArg` is
309
- * @returns The `every` method is returning a boolean value. It returns `true` if every element in
310
- * the array satisfies the provided predicate function, and `false` otherwise.
311
- */
312
- every(predicate, thisArg) {
313
- let index = 0;
314
- for (const item of this) {
315
- if (!predicate.call(thisArg, item, index++, this)) {
316
- return false;
317
- }
318
- }
319
- return true;
320
- }
321
- /**
322
- * Time Complexity: O(n)
323
- * Space Complexity: O(1)
324
- *
325
- * The "some" function checks if at least one element in a collection satisfies a given predicate.
326
- * @param predicate - The `predicate` parameter is a callback function that takes three arguments:
327
- * `value`, `index`, and `array`. It should return a boolean value indicating whether the current
328
- * element satisfies the condition.
329
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that specifies the value
330
- * to be used as the `this` value when executing the `predicate` function. If `thisArg` is provided,
331
- * it will be passed as the `this` value to the `predicate` function. If `thisArg
332
- * @returns a boolean value. It returns true if the predicate function returns true for any element
333
- * in the collection, and false otherwise.
334
- */
335
- some(predicate, thisArg) {
336
- let index = 0;
337
- for (const item of this) {
338
- if (predicate.call(thisArg, item, index++, this)) {
339
- return true;
340
- }
341
- }
342
- return false;
343
- }
344
- /**
345
- * Time Complexity: O(n)
346
- * Space Complexity: O(1)
347
- *
348
- * The `forEach` function iterates over each element in an array-like object and calls a callback
349
- * function for each element.
350
- * @param callbackfn - The callbackfn parameter is a function that will be called for each element in
351
- * the array. It takes three arguments: the current element being processed, the index of the current
352
- * element, and the array that forEach was called upon.
353
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that specifies the value
354
- * to be used as `this` when executing the `callbackfn` function. If `thisArg` is provided, it will
355
- * be passed as the `this` value to the `callbackfn` function. If `thisArg
356
- */
357
- forEach(callbackfn, thisArg) {
358
- let index = 0;
359
- for (const item of this) {
360
- callbackfn.call(thisArg, item, index++, this);
361
- }
362
- }
363
- /**
364
- * Time Complexity: O(n)
365
- * Space Complexity: O(1)
366
- *
367
- * The `find` function iterates over the elements of an array-like object and returns the first
368
- * element that satisfies the provided callback function.
369
- * @param predicate - The predicate parameter is a function that will be called for each element in
370
- * the array. It takes three arguments: the current element being processed, the index of the current
371
- * element, and the array itself. The function should return a boolean value indicating whether the
372
- * current element matches the desired condition.
373
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that specifies the value
374
- * to be used as `this` when executing the `callbackfn` function. If `thisArg` is provided, it will
375
- * be passed as the `this` value to the `callbackfn` function. If `thisArg
376
- * @returns The `find` method returns the first element in the array that satisfies the provided
377
- * callback function. If no element satisfies the callback function, `undefined` is returned.
378
- */
379
- find(predicate, thisArg) {
380
- let index = 0;
381
- for (const item of this) {
382
- if (predicate.call(thisArg, item, index++, this)) return item;
383
- }
384
- return;
385
- }
386
- /**
387
- * Time Complexity: O(n)
388
- * Space Complexity: O(1)
389
- *
390
- * The function checks if a given element exists in a collection.
391
- * @param {E} element - The parameter "element" is of type E, which means it can be any type. It
392
- * represents the element that we want to check for existence in the collection.
393
- * @returns a boolean value. It returns true if the element is found in the collection, and false
394
- * otherwise.
395
- */
396
- has(element) {
397
- for (const ele of this) {
398
- if (ele === element) return true;
399
- }
400
- return false;
401
- }
402
- /**
403
- * Time Complexity: O(n)
404
- * Space Complexity: O(1)
405
- *
406
- * The `reduce` function iterates over the elements of an array-like object and applies a callback
407
- * function to reduce them into a single value.
408
- * @param callbackfn - The callbackfn parameter is a function that will be called for each element in
409
- * the array. It takes four arguments:
410
- * @param {U} initialValue - The initialValue parameter is the initial value of the accumulator. It
411
- * is the value that the accumulator starts with before the reduction operation begins.
412
- * @returns The `reduce` method is returning the final value of the accumulator after iterating over
413
- * all the elements in the array and applying the callback function to each element.
414
- */
415
- reduce(callbackfn, initialValue) {
416
- let accumulator = initialValue ?? 0;
417
- let index = 0;
418
- for (const item of this) {
419
- accumulator = callbackfn(accumulator, item, index++, this);
420
- }
421
- return accumulator;
422
- }
423
- /**
424
- * Time Complexity: O(n)
425
- * Space Complexity: O(n)
426
- *
427
- * The `toArray` function converts a linked list into an array.
428
- * @returns The `toArray()` method is returning an array of type `E[]`.
429
- */
430
- toArray() {
431
- return [...this];
432
- }
433
- /**
434
- * Time Complexity: O(n)
435
- * Space Complexity: O(n)
436
- *
437
- * The print function logs the elements of an array to the console.
438
- */
439
- toVisual() {
440
- return [...this];
441
- }
442
- /**
443
- * Time Complexity: O(n)
444
- * Space Complexity: O(n)
445
- *
446
- * The print function logs the elements of an array to the console.
447
- */
448
- print() {
449
- console.log(this.toVisual());
450
- }
451
- };
452
-
453
- // src/data-structures/heap/heap.ts
454
- var Heap = class _Heap extends IterableElementBase {
455
- /**
456
- * The constructor initializes a heap data structure with optional elements and options.
457
- * @param elements - The `elements` parameter is an iterable object that contains the initial
458
- * elements to be added to the heap.
459
- * It is an optional parameter, and if not provided, the heap will
460
- * be initialized as empty.
461
- * @param [options] - The `options` parameter is an optional object that can contain additional
462
- * configuration options for the heap.
463
- * In this case, it is used to specify a custom comparator
464
- * function for comparing elements in the heap.
465
- * The comparator function is used to determine the
466
- * order of elements in the heap.
467
- */
468
- constructor(elements = [], options) {
469
- super(options);
470
- if (options) {
471
- const { comparator } = options;
472
- if (comparator) this._comparator = comparator;
473
- }
474
- this.addMany(elements);
475
- }
476
- _elements = [];
477
- /**
478
- * The function returns an array of elements.
479
- * @returns The element array is being returned.
480
- */
481
- get elements() {
482
- return this._elements;
483
- }
484
- /**
485
- * Get the size (number of elements) of the heap.
486
- */
487
- get size() {
488
- return this.elements.length;
489
- }
490
- /**
491
- * Get the last element in the heap, which is not necessarily a leaf node.
492
- * @returns The last element or undefined if the heap is empty.
493
- */
494
- get leaf() {
495
- return this.elements[this.size - 1] ?? void 0;
496
- }
497
- /**
498
- * Static method that creates a binary heap from an array of elements and a comparison function.
499
- * @returns A new Heap instance.
500
- * @param elements
501
- * @param options
502
- */
503
- static heapify(elements, options) {
504
- return new _Heap(elements, options);
505
- }
506
- /**
507
- * Time Complexity: O(log n)
508
- * Space Complexity: O(1)
509
- *
510
- * The add function pushes an element into an array and then triggers a bubble-up operation.
511
- * @param {E} element - The `element` parameter represents the element that you want to add to the
512
- * data structure.
513
- * @returns The `add` method is returning a boolean value, which is the result of calling the
514
- * `_bubbleUp` method with the index `this.elements.length - 1` as an argument.
515
- */
516
- add(element) {
517
- this._elements.push(element);
518
- return this._bubbleUp(this.elements.length - 1);
519
- }
520
- /**
521
- * Time Complexity: O(k log n)
522
- * Space Complexity: O(1)
523
- *
524
- * The `addMany` function iterates over elements and adds them to a collection, returning an array of
525
- * boolean values indicating success or failure.
526
- * @param {Iterable<E> | Iterable<R>} elements - The `elements` parameter in the `addMany` method is
527
- * an iterable containing elements of type `E` or `R`. The method iterates over each element in the
528
- * iterable and adds them to the data structure. If a transformation function `_toElementFn` is
529
- * provided, it transforms the element
530
- * @returns The `addMany` method returns an array of boolean values indicating whether each element
531
- * in the input iterable was successfully added to the data structure.
532
- */
533
- addMany(elements) {
534
- const ans = [];
535
- for (const el of elements) {
536
- if (this._toElementFn) {
537
- ans.push(this.add(this._toElementFn(el)));
538
- continue;
539
- }
540
- ans.push(this.add(el));
541
- }
542
- return ans;
543
- }
544
- /**
545
- * Time Complexity: O(log n)
546
- * Space Complexity: O(1)
547
- *
548
- * Remove and return the top element (the smallest or largest element) from the heap.
549
- * @returns The top element or undefined if the heap is empty.
550
- */
551
- poll() {
552
- if (this.elements.length === 0) return;
553
- const value = this.elements[0];
554
- const last = this.elements.pop();
555
- if (this.elements.length) {
556
- this.elements[0] = last;
557
- this._sinkDown(0, this.elements.length >> 1);
558
- }
559
- return value;
560
- }
561
- /**
562
- * Time Complexity: O(1)
563
- * Space Complexity: O(1)
564
- *
565
- * Peek at the top element of the heap without removing it.
566
- * @returns The top element or undefined if the heap is empty.
567
- */
568
- peek() {
569
- return this.elements[0];
570
- }
571
- /**
572
- * Check if the heap is empty.
573
- * @returns True if the heap is empty, otherwise false.
574
- */
575
- isEmpty() {
576
- return this.size === 0;
577
- }
578
- /**
579
- * Reset the elements of the heap. Make the elements empty.
580
- */
581
- clear() {
582
- this._elements = [];
583
- }
584
- /**
585
- * Time Complexity: O(n)
586
- * Space Complexity: O(n)
587
- *
588
- * Clear and add elements of the heap
589
- * @param elements
590
- */
591
- refill(elements) {
592
- this._elements = elements;
593
- return this.fix();
594
- }
595
- /**
596
- * Time Complexity: O(n)
597
- * Space Complexity: O(1)
598
- *
599
- * Use a comparison function to check whether a binary heap contains a specific element.
600
- * @param element - the element to check.
601
- * @returns Returns true if the specified element is contained; otherwise, returns false.
602
- */
603
- has(element) {
604
- return this.elements.includes(element);
605
- }
606
- /**
607
- * Time Complexity: O(n)
608
- * Space Complexity: O(1)
609
- *
610
- * The `delete` function removes an element from an array-like data structure, maintaining the order
611
- * and structure of the remaining elements.
612
- * @param {E} element - The `element` parameter represents the element that you want to delete from
613
- * the array `this.elements`.
614
- * @returns The `delete` function is returning a boolean value. It returns `true` if the element was
615
- * successfully deleted from the array, and `false` if the element was not found in the array.
616
- */
617
- delete(element) {
618
- const index = this.elements.indexOf(element);
619
- if (index < 0) return false;
620
- if (index === 0) {
621
- this.poll();
622
- } else if (index === this.elements.length - 1) {
623
- this.elements.pop();
624
- } else {
625
- this.elements.splice(index, 1, this.elements.pop());
626
- this._bubbleUp(index);
627
- this._sinkDown(index, this.elements.length >> 1);
628
- }
629
- return true;
630
- }
631
- /**
632
- * Time Complexity: O(n)
633
- * Space Complexity: O(log n)
634
- *
635
- * Depth-first search (DFS) method, different traversal orders can be selected。
636
- * @param order - Traverse order parameter: 'IN' (in-order), 'PRE' (pre-order) or 'POST' (post-order).
637
- * @returns An array containing elements traversed in the specified order.
638
- */
639
- dfs(order = "PRE") {
640
- const result = [];
641
- const _dfs = (index) => {
642
- const left = 2 * index + 1, right = left + 1;
643
- if (index < this.size) {
644
- if (order === "IN") {
645
- _dfs(left);
646
- result.push(this.elements[index]);
647
- _dfs(right);
648
- } else if (order === "PRE") {
649
- result.push(this.elements[index]);
650
- _dfs(left);
651
- _dfs(right);
652
- } else if (order === "POST") {
653
- _dfs(left);
654
- _dfs(right);
655
- result.push(this.elements[index]);
656
- }
657
- }
658
- };
659
- _dfs(0);
660
- return result;
661
- }
662
- /**
663
- * Time Complexity: O(n)
664
- * Space Complexity: O(n)
665
- *
666
- * Clone the heap, creating a new heap with the same elements.
667
- * @returns A new Heap instance containing the same elements.
668
- */
669
- clone() {
670
- return new _Heap(this, { comparator: this.comparator, toElementFn: this.toElementFn });
671
- }
672
- /**
673
- * Time Complexity: O(n log n)
674
- * Space Complexity: O(n)
675
- *
676
- * Sort the elements in the heap and return them as an array.
677
- * @returns An array containing the elements sorted in ascending order.
678
- */
679
- sort() {
680
- const visitedNode = [];
681
- const cloned = new _Heap(this, { comparator: this.comparator });
682
- while (cloned.size !== 0) {
683
- const top = cloned.poll();
684
- if (top !== void 0) visitedNode.push(top);
685
- }
686
- return visitedNode;
687
- }
688
- /**
689
- * Time Complexity: O(n log n)
690
- * Space Complexity: O(n)
691
- *
692
- * Fix the entire heap to maintain heap properties.
693
- */
694
- fix() {
695
- const results = [];
696
- for (let i = Math.floor(this.size / 2); i >= 0; i--) results.push(this._sinkDown(i, this.elements.length >> 1));
697
- return results;
698
- }
699
- /**
700
- * Time Complexity: O(n)
701
- * Space Complexity: O(n)
702
- *
703
- * The `filter` function creates a new Heap object containing elements that pass a given callback
704
- * function.
705
- * @param callback - The `callback` parameter is a function that will be called for each element in
706
- * the heap. It takes three arguments: the current element, the index of the current element, and the
707
- * heap itself. The callback function should return a boolean value indicating whether the current
708
- * element should be included in the filtered list
709
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that specifies the value
710
- * to be used as `this` when executing the `callback` function. If `thisArg` is provided, it will be
711
- * passed as the `this` value to the `callback` function. If `thisArg` is
712
- * @returns The `filter` method is returning a new `Heap` object that contains the elements that pass
713
- * the filter condition specified by the `callback` function.
714
- */
715
- filter(callback, thisArg) {
716
- const filteredList = new _Heap([], { toElementFn: this.toElementFn, comparator: this.comparator });
717
- let index = 0;
718
- for (const current of this) {
719
- if (callback.call(thisArg, current, index, this)) {
720
- filteredList.add(current);
721
- }
722
- index++;
723
- }
724
- return filteredList;
725
- }
726
- /**
727
- * Time Complexity: O(n)
728
- * Space Complexity: O(n)
729
- *
730
- * The `map` function creates a new heap by applying a callback function to each element of the
731
- * original heap.
732
- * @param callback - The `callback` parameter is a function that will be called for each element in
733
- * the heap. It takes three arguments: `el` (the current element), `index` (the index of the current
734
- * element), and `this` (the heap itself). The callback function should return a value of
735
- * @param comparator - The `comparator` parameter is a function that defines the order of the
736
- * elements in the heap. It takes two elements `a` and `b` as arguments and returns a negative number
737
- * if `a` should be placed before `b`, a positive number if `a` should be placed after
738
- * @param [toElementFn] - The `toElementFn` parameter is an optional function that converts the raw
739
- * element `RR` to the desired type `T`. It takes a single argument `rawElement` of type `RR` and
740
- * returns a value of type `T`. This function is used to transform the elements of the original
741
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that allows you to
742
- * specify the value of `this` within the callback function. It is used to set the context or scope
743
- * in which the callback function will be executed. If `thisArg` is provided, it will be used as the
744
- * value of
745
- * @returns a new instance of the `Heap` class with the mapped elements.
746
- */
747
- map(callback, comparator, toElementFn, thisArg) {
748
- const mappedHeap = new _Heap([], { comparator, toElementFn });
749
- let index = 0;
750
- for (const el of this) {
751
- mappedHeap.add(callback.call(thisArg, el, index, this));
752
- index++;
753
- }
754
- return mappedHeap;
755
- }
756
- _DEFAULT_COMPARATOR = (a, b) => {
757
- if (typeof a === "object" || typeof b === "object") {
758
- throw TypeError(
759
- `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`
760
- );
761
- }
762
- if (a > b) return 1;
763
- if (a < b) return -1;
764
- return 0;
765
- };
766
- _comparator = this._DEFAULT_COMPARATOR;
767
- /**
768
- * The function returns the value of the _comparator property.
769
- * @returns The `_comparator` property is being returned.
770
- */
771
- get comparator() {
772
- return this._comparator;
773
- }
774
- /**
775
- * The function `_getIterator` returns an iterable iterator for the elements in the class.
776
- */
777
- *_getIterator() {
778
- for (const element of this.elements) {
779
- yield element;
780
- }
781
- }
782
- /**
783
- * Time Complexity: O(log n)
784
- * Space Complexity: O(1)
785
- *
786
- * Float operation to maintain heap properties after adding an element.
787
- * @param index - The index of the newly added element.
788
- */
789
- _bubbleUp(index) {
790
- const element = this.elements[index];
791
- while (index > 0) {
792
- const parent = index - 1 >> 1;
793
- const parentItem = this.elements[parent];
794
- if (this.comparator(parentItem, element) <= 0) break;
795
- this.elements[index] = parentItem;
796
- index = parent;
797
- }
798
- this.elements[index] = element;
799
- return true;
800
- }
801
- /**
802
- * Time Complexity: O(log n)
803
- * Space Complexity: O(1)
804
- *
805
- * Sinking operation to maintain heap properties after removing the top element.
806
- * @param index - The index from which to start sinking.
807
- * @param halfLength
808
- */
809
- _sinkDown(index, halfLength) {
810
- const element = this.elements[index];
811
- while (index < halfLength) {
812
- let left = index << 1 | 1;
813
- const right = left + 1;
814
- let minItem = this.elements[left];
815
- if (right < this.elements.length && this.comparator(minItem, this.elements[right]) > 0) {
816
- left = right;
817
- minItem = this.elements[right];
818
- }
819
- if (this.comparator(minItem, element) >= 0) break;
820
- this.elements[index] = minItem;
821
- index = left;
822
- }
823
- this.elements[index] = element;
824
- return true;
825
- }
826
- };
827
-
828
- // src/data-structures/base/linear-base.ts
829
- var LinearBase = class _LinearBase extends IterableElementBase {
830
- /**
831
- * The constructor initializes the LinearBase class with optional options, setting the maximum length
832
- * if provided.
833
- * @param [options] - The `options` parameter is an optional object that can be passed to the
834
- * constructor. It is of type `LinearBaseOptions<E, R>`. The constructor checks if the `options`
835
- * object is provided and then extracts the `maxLen` property from it. If `maxLen` is a
836
- */
837
- constructor(options) {
838
- super(options);
839
- if (options) {
840
- const { maxLen } = options;
841
- if (typeof maxLen === "number" && maxLen > 0 && maxLen % 1 === 0) this._maxLen = maxLen;
842
- }
843
- }
844
- _maxLen = -1;
845
- get maxLen() {
846
- return this._maxLen;
847
- }
848
- /**
849
- * Time Complexity: O(n)
850
- * Space Complexity: O(1)
851
- *
852
- * The function indexOf searches for a specified element starting from a given index in an array-like
853
- * object and returns the index of the first occurrence, or -1 if not found.
854
- * @param {E} searchElement - The `searchElement` parameter in the `indexOf` function represents the
855
- * element that you want to find within the array. The function will search for this element starting
856
- * from the `fromIndex` (if provided) up to the end of the array. If the `searchElement` is found
857
- * within the
858
- * @param {number} [fromIndex=0] - The `fromIndex` parameter in the `indexOf` function represents the
859
- * index at which to start searching for the `searchElement` within the array. If provided, the
860
- * search will begin at this index and continue to the end of the array. If `fromIndex` is not
861
- * specified, the default
862
- * @returns The `indexOf` method is returning the index of the `searchElement` if it is found in the
863
- * array starting from the `fromIndex`. If the `searchElement` is not found, it returns -1.
864
- */
865
- indexOf(searchElement, fromIndex = 0) {
866
- if (this.length === 0) return -1;
867
- if (fromIndex < 0) fromIndex = this.length + fromIndex;
868
- if (fromIndex < 0) fromIndex = 0;
869
- for (let i = fromIndex; i < this.length; i++) {
870
- const element = this.at(i);
871
- if (element === searchElement) return i;
872
- }
873
- return -1;
874
- }
875
- /**
876
- * Time Complexity: O(n)
877
- * Space Complexity: O(1)
878
- *
879
- * The function `lastIndexOf` in TypeScript returns the index of the last occurrence of a specified
880
- * element in an array.
881
- * @param {E} searchElement - The `searchElement` parameter is the element that you want to find the
882
- * last index of within the array. The `lastIndexOf` method will search the array starting from the
883
- * `fromIndex` (or the end of the array if not specified) and return the index of the last occurrence
884
- * of the
885
- * @param {number} fromIndex - The `fromIndex` parameter in the `lastIndexOf` method specifies the
886
- * index at which to start searching for the `searchElement` in the array. By default, it starts
887
- * searching from the last element of the array (`this.length - 1`). If a specific `fromIndex` is
888
- * provided
889
- * @returns The last index of the `searchElement` in the array is being returned. If the
890
- * `searchElement` is not found in the array, -1 is returned.
891
- */
892
- lastIndexOf(searchElement, fromIndex = this.length - 1) {
893
- if (this.length === 0) return -1;
894
- if (fromIndex >= this.length) fromIndex = this.length - 1;
895
- if (fromIndex < 0) fromIndex = this.length + fromIndex;
896
- for (let i = fromIndex; i >= 0; i--) {
897
- const element = this.at(i);
898
- if (element === searchElement) return i;
899
- }
900
- return -1;
901
- }
902
- /**
903
- * Time Complexity: O(n)
904
- * Space Complexity: O(1)
905
- *
906
- * The `findIndex` function iterates over an array and returns the index of the first element that
907
- * satisfies the provided predicate function.
908
- * @param predicate - The `predicate` parameter in the `findIndex` function is a callback function
909
- * that takes three arguments: `item`, `index`, and the array `this`. It should return a boolean
910
- * value indicating whether the current element satisfies the condition being checked for.
911
- * @param {any} [thisArg] - The `thisArg` parameter in the `findIndex` function is an optional
912
- * parameter that specifies the value to use as `this` when executing the `predicate` function. If
913
- * provided, the `predicate` function will be called with `thisArg` as its `this` value. If `
914
- * @returns The `findIndex` method is returning the index of the first element in the array that
915
- * satisfies the provided predicate function. If no such element is found, it returns -1.
916
- */
917
- findIndex(predicate, thisArg) {
918
- for (let i = 0; i < this.length; i++) {
919
- const item = this.at(i);
920
- if (item !== void 0 && predicate.call(thisArg, item, i, this)) return i;
921
- }
922
- return -1;
923
- }
924
- /**
925
- * Time Complexity: O(n + m)
926
- * Space Complexity: O(n + m)
927
- *
928
- * The `concat` function in TypeScript concatenates multiple items into a new list, handling both
929
- * individual elements and instances of `LinearBase`.
930
- * @param {(E | this)[]} items - The `concat` method takes in an array of items, where
931
- * each item can be either of type `E` or an instance of `LinearBase<E, R>`.
932
- * @returns The `concat` method is returning a new instance of the class that it belongs to, with the
933
- * items passed as arguments concatenated to it.
934
- */
935
- concat(...items) {
936
- const newList = this.clone();
937
- for (const item of items) {
938
- if (item instanceof _LinearBase) {
939
- newList.pushMany(item);
940
- } else {
941
- newList.push(item);
942
- }
943
- }
944
- return newList;
945
- }
946
- /**
947
- * Time Complexity: O(n log n)
948
- * Space Complexity: O(n)
949
- *
950
- * The `sort` function in TypeScript sorts the elements of a collection using a specified comparison
951
- * function.
952
- * @param [compareFn] - The `compareFn` parameter is a function that defines the sort order. It takes
953
- * two elements `a` and `b` as input and returns a number indicating their relative order. If the
954
- * returned value is negative, `a` comes before `b`. If the returned value is positive, `
955
- * @returns The `sort` method is returning the instance of the object on which it is called (this),
956
- * after sorting the elements based on the provided comparison function (compareFn).
957
- */
958
- sort(compareFn) {
959
- const arr = this.toArray();
960
- arr.sort(compareFn);
961
- this.clear();
962
- for (const item of arr) this.push(item);
963
- return this;
964
- }
965
- /**
966
- * Time Complexity: O(n + m)
967
- * Space Complexity: O(m)
968
- *
969
- * The `splice` function in TypeScript removes elements from an array and optionally inserts new
970
- * elements at the specified index.
971
- * @param {number} start - The `start` parameter in the `splice` method indicates the index at which
972
- * to start modifying the array. If `start` is a negative number, it will count from the end of the
973
- * array.
974
- * @param {number} [deleteCount=0] - The `deleteCount` parameter in the `splice` method specifies the
975
- * number of elements to remove from the array starting at the specified `start` index. If
976
- * `deleteCount` is not provided or is 0, no elements are removed, and only new elements are inserted
977
- * at the `start`
978
- * @param {E[]} items - The `items` parameter in the `splice` method represents the elements that
979
- * will be inserted into the array at the specified `start` index. These elements can be of any type
980
- * and you can pass multiple elements separated by commas. The `splice` method will insert these
981
- * items into the array at the
982
- * @returns The `splice` method returns a list of elements that were removed from the original list
983
- * during the operation.
984
- */
985
- splice(start, deleteCount = 0, ...items) {
986
- const removedList = this._createInstance();
987
- start = start < 0 ? this.length + start : start;
988
- start = Math.max(0, Math.min(start, this.length));
989
- deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));
990
- for (let i = 0; i < deleteCount; i++) {
991
- const removed = this.deleteAt(start);
992
- if (removed !== void 0) {
993
- removedList.push(removed);
994
- }
995
- }
996
- for (let i = 0; i < items.length; i++) {
997
- this.addAt(start + i, items[i]);
998
- }
999
- return removedList;
1000
- }
1001
- /**
1002
- * Time Complexity: O(n)
1003
- * Space Complexity: O(1)
1004
- *
1005
- * The `join` function in TypeScript returns a string by joining the elements of an array with a
1006
- * specified separator.
1007
- * @param {string} [separator=,] - The `separator` parameter is a string that specifies the character
1008
- * or characters that will be used to separate each element when joining them into a single string.
1009
- * By default, the separator is set to a comma (`,`), but you can provide a different separator if
1010
- * needed.
1011
- * @returns The `join` method is being returned, which takes an optional `separator` parameter
1012
- * (defaulting to a comma) and returns a string created by joining all elements of the array after
1013
- * converting it to an array.
1014
- */
1015
- join(separator = ",") {
1016
- return this.toArray().join(separator);
1017
- }
1018
- /**
1019
- * Time Complexity: O(n)
1020
- * Space Complexity: O(n)
1021
- *
1022
- * The function `toReversedArray` takes an array and returns a new array with its elements in reverse
1023
- * order.
1024
- * @returns The `toReversedArray()` function returns an array of elements of type `E` in reverse
1025
- * order.
1026
- */
1027
- toReversedArray() {
1028
- const array = [];
1029
- for (let i = this.length - 1; i >= 0; i--) {
1030
- array.push(this.at(i));
1031
- }
1032
- return array;
1033
- }
1034
- /**
1035
- * Time Complexity: O(n)
1036
- * Space Complexity: O(1)
1037
- *
1038
- * The `reduceRight` function in TypeScript iterates over an array from right to left and applies a
1039
- * callback function to each element, accumulating a single result.
1040
- * @param callbackfn - The `callbackfn` parameter in the `reduceRight` method is a function that will
1041
- * be called on each element in the array from right to left. It takes four arguments:
1042
- * @param {U} [initialValue] - The `initialValue` parameter in the `reduceRight` method is an
1043
- * optional parameter that specifies the initial value of the accumulator. If provided, the
1044
- * `accumulator` will start with this initial value before iterating over the elements of the array.
1045
- * If `initialValue` is not provided, the accumulator will
1046
- * @returns The `reduceRight` method is returning the final accumulated value after applying the
1047
- * callback function to each element in the array from right to left.
1048
- */
1049
- reduceRight(callbackfn, initialValue) {
1050
- let accumulator = initialValue ?? 0;
1051
- for (let i = this.length - 1; i >= 0; i--) {
1052
- accumulator = callbackfn(accumulator, this.at(i), i, this);
1053
- }
1054
- return accumulator;
1055
- }
1056
- /**
1057
- * Time Complexity: O(m)
1058
- * Space Complexity: O(m)
1059
- *
1060
- * The `slice` function in TypeScript creates a new instance by extracting a portion of elements from
1061
- * the original instance based on the specified start and end indices.
1062
- * @param {number} [start=0] - The `start` parameter in the `slice` method represents the index at
1063
- * which to begin extracting elements from an array-like object. If no `start` parameter is provided,
1064
- * the default value is 0, meaning the extraction will start from the beginning of the array.
1065
- * @param {number} end - The `end` parameter in the `slice` method represents the index at which to
1066
- * end the slicing. By default, if no `end` parameter is provided, it will slice until the end of the
1067
- * array (i.e., `this.length`).
1068
- * @returns The `slice` method is returning a new instance of the object with elements sliced from
1069
- * the specified start index (default is 0) to the specified end index (default is the length of the
1070
- * object).
1071
- */
1072
- slice(start = 0, end = this.length) {
1073
- start = start < 0 ? this.length + start : start;
1074
- end = end < 0 ? this.length + end : end;
1075
- const newList = this._createInstance();
1076
- for (let i = start; i < end; i++) {
1077
- newList.push(this.at(i));
1078
- }
1079
- return newList;
1080
- }
1081
- /**
1082
- * Time Complexity: O(n)
1083
- * Space Complexity: O(1)
1084
- *
1085
- * The `fill` function in TypeScript fills a specified range in an array-like object with a given
1086
- * value.
1087
- * @param {E} value - The `value` parameter in the `fill` method represents the element that will be
1088
- * used to fill the specified range in the array.
1089
- * @param [start=0] - The `start` parameter specifies the index at which to start filling the array
1090
- * with the specified value. If not provided, it defaults to 0, indicating the beginning of the
1091
- * array.
1092
- * @param end - The `end` parameter in the `fill` function represents the index at which the filling
1093
- * of values should stop. It specifies the end of the range within the array where the `value` should
1094
- * be filled.
1095
- * @returns The `fill` method is returning the modified object (`this`) after filling the specified
1096
- * range with the provided value.
1097
- */
1098
- fill(value, start = 0, end = this.length) {
1099
- start = start < 0 ? this.length + start : start;
1100
- end = end < 0 ? this.length + end : end;
1101
- if (start < 0) start = 0;
1102
- if (end > this.length) end = this.length;
1103
- if (start >= end) return this;
1104
- for (let i = start; i < end; i++) {
1105
- this.setAt(i, value);
1106
- }
1107
- return this;
1108
- }
1109
- };
1110
-
1111
- // src/data-structures/queue/queue.ts
1112
- var Queue = class _Queue extends LinearBase {
1113
- constructor(elements = [], options) {
1114
- super(options);
1115
- if (options) {
1116
- const { autoCompactRatio = 0.5 } = options;
1117
- this._autoCompactRatio = autoCompactRatio;
1118
- }
1119
- this.pushMany(elements);
1120
- }
1121
- _elements = [];
1122
- get elements() {
1123
- return this._elements;
1124
- }
1125
- _offset = 0;
1126
- get offset() {
1127
- return this._offset;
1128
- }
1129
- get length() {
1130
- return this.elements.length - this.offset;
1131
- }
1132
- _autoCompactRatio = 0.5;
1133
- get autoCompactRatio() {
1134
- return this._autoCompactRatio;
1135
- }
1136
- set autoCompactRatio(v) {
1137
- this._autoCompactRatio = v;
1138
- }
1139
- /**
1140
- * Time Complexity: O(1)
1141
- * Space Complexity: O(1)
1142
- *
1143
- * The `first` function returns the first element of the array `_elements` if it exists, otherwise it returns `undefined`.
1144
- * @returns The `get first()` method returns the first element of the data structure, represented by the `_elements` array at
1145
- * the `_offset` index. If the data structure is empty (length is 0), it returns `undefined`.
1146
- */
1147
- get first() {
1148
- return this.length > 0 ? this.elements[this.offset] : void 0;
1149
- }
1150
- /**
1151
- * Time Complexity: O(1)
1152
- * Space Complexity: O(1)
1153
- *
1154
- * The `last` function returns the last element in an array-like data structure, or undefined if the structure is empty.
1155
- * @returns The method `get last()` returns the last element of the `_elements` array if the array is not empty. If the
1156
- * array is empty, it returns `undefined`.
1157
- */
1158
- get last() {
1159
- return this.length > 0 ? this.elements[this.elements.length - 1] : void 0;
1160
- }
1161
- /**
1162
- * Time Complexity: O(n)
1163
- * Space Complexity: O(n)
1164
- *
1165
- * The function "fromArray" creates a new Queue object from an array of elements.Creates a queue from an existing array.
1166
- * @public
1167
- * @param {E[]} elements - The "elements" parameter is an array of elements of type E.
1168
- * @returns The method is returning a new instance of the Queue class, initialized with the elements from the input
1169
- * array.
1170
- */
1171
- static fromArray(elements) {
1172
- return new _Queue(elements);
1173
- }
1174
- /**
1175
- * Time Complexity: O(1)
1176
- * Space Complexity: O(1)
1177
- *
1178
- * The push function adds an element to the end of the queue and returns true. Adds an element at the back of the queue.
1179
- * @param {E} element - The `element` parameter represents the element that you want to add to the queue.
1180
- * @returns Always returns true, indicating the element was successfully added.
1181
- */
1182
- push(element) {
1183
- this.elements.push(element);
1184
- if (this._maxLen > 0 && this.length > this._maxLen) this.shift();
1185
- return true;
1186
- }
1187
- /**
1188
- * Time Complexity: O(k)
1189
- * Space Complexity: O(k)
1190
- *
1191
- * The `pushMany` function iterates over elements and pushes them into an array after applying a
1192
- * transformation function if provided.
1193
- * @param {Iterable<E> | Iterable<R>} elements - The `elements` parameter in the `pushMany` function
1194
- * is an iterable containing elements of type `E` or `R`.
1195
- * @returns The `pushMany` function is returning an array of boolean values indicating whether each
1196
- * element was successfully pushed into the data structure.
1197
- */
1198
- pushMany(elements) {
1199
- const ans = [];
1200
- for (const el of elements) {
1201
- if (this.toElementFn) ans.push(this.push(this.toElementFn(el)));
1202
- else ans.push(this.push(el));
1203
- }
1204
- return ans;
1205
- }
1206
- /**
1207
- * Time Complexity: O(1)
1208
- * Space Complexity: O(1)
1209
- *
1210
- * The `shift` function removes and returns the first element in the queue, and adjusts the internal data structure if
1211
- * necessary to optimize performance.
1212
- * @returns The function `shift()` returns either the first element in the queue or `undefined` if the queue is empty.
1213
- */
1214
- shift() {
1215
- if (this.length === 0) return void 0;
1216
- const first = this.first;
1217
- this._offset += 1;
1218
- if (this.offset / this.elements.length > this.autoCompactRatio) this.compact();
1219
- return first;
1220
- }
1221
- /**
1222
- * Time Complexity: O(n)
1223
- * Space Complexity: O(1)
1224
- *
1225
- * The delete function removes an element from the list.
1226
- * @param {E} element - Specify the element to be deleted
1227
- * @return A boolean value indicating whether the element was successfully deleted or not
1228
- */
1229
- delete(element) {
1230
- const index = this.elements.indexOf(element);
1231
- return !!this.deleteAt(index);
1232
- }
1233
- /**
1234
- * Time Complexity: O(n)
1235
- * Space Complexity: O(1)
1236
- *
1237
- * The deleteAt function deletes the element at a given index.
1238
- * @param {number} index - Determine the index of the element to be deleted
1239
- * @return A boolean value
1240
- */
1241
- deleteAt(index) {
1242
- const deleted = this.elements[index];
1243
- this.elements.splice(index, 1);
1244
- return deleted;
1245
- }
1246
- /**
1247
- * Time Complexity: O(1)
1248
- * Space Complexity: O(1)
1249
- *
1250
- * The `at` function returns the element at a specified index adjusted by an offset, or `undefined`
1251
- * if the index is out of bounds.
1252
- * @param {number} index - The `index` parameter represents the position of the element you want to
1253
- * retrieve from the data structure.
1254
- * @returns The `at` method is returning the element at the specified index adjusted by the offset
1255
- * `_offset`.
1256
- */
1257
- at(index) {
1258
- return this.elements[index + this._offset];
1259
- }
1260
- /**
1261
- * Time Complexity: O(n)
1262
- * Space Complexity: O(1)
1263
- *
1264
- * The `reverse` function in TypeScript reverses the elements of an array starting from a specified
1265
- * offset.
1266
- * @returns The `reverse()` method is returning the modified object itself (`this`) after reversing
1267
- * the elements in the array and resetting the offset to 0.
1268
- */
1269
- reverse() {
1270
- this._elements = this.elements.slice(this.offset).reverse();
1271
- this._offset = 0;
1272
- return this;
1273
- }
1274
- /**
1275
- * Time Complexity: O(n)
1276
- * Space Complexity: O(1)
1277
- *
1278
- * The function `addAt` inserts a new element at a specified index in an array, returning true if
1279
- * successful and false if the index is out of bounds.
1280
- * @param {number} index - The `index` parameter represents the position at which the `newElement`
1281
- * should be added in the array.
1282
- * @param {E} newElement - The `newElement` parameter represents the element that you want to insert
1283
- * into the array at the specified index.
1284
- * @returns The `addAt` method returns a boolean value - `true` if the new element was successfully
1285
- * added at the specified index, and `false` if the index is out of bounds (less than 0 or greater
1286
- * than the length of the array).
1287
- */
1288
- addAt(index, newElement) {
1289
- if (index < 0 || index > this.length) return false;
1290
- this._elements.splice(this.offset + index, 0, newElement);
1291
- return true;
1292
- }
1293
- /**
1294
- * Time Complexity: O(1)
1295
- * Space Complexity: O(1)
1296
- *
1297
- * The function `setAt` updates an element at a specified index in an array-like data structure.
1298
- * @param {number} index - The `index` parameter is a number that represents the position in the
1299
- * array where the new element will be set.
1300
- * @param {E} newElement - The `newElement` parameter represents the new value that you want to set
1301
- * at the specified index in the array.
1302
- * @returns The `setAt` method returns a boolean value - `true` if the element was successfully set
1303
- * at the specified index, and `false` if the index is out of bounds (less than 0 or greater than the
1304
- * length of the array).
1305
- */
1306
- setAt(index, newElement) {
1307
- if (index < 0 || index > this.length) return false;
1308
- this._elements[this.offset + index] = newElement;
1309
- return true;
1310
- }
1311
- /**
1312
- * Time Complexity: O(1)
1313
- * Space Complexity: O(1)
1314
- *
1315
- * The function checks if a data structure is empty by comparing its length to zero.
1316
- * @returns {boolean} A boolean value indicating whether the length of the object is 0 or not.
1317
- */
1318
- isEmpty() {
1319
- return this.length === 0;
1320
- }
1321
- /**
1322
- * Time Complexity: O(1)
1323
- * Space Complexity: O(1)
1324
- *
1325
- * The clear function resets the elements array and offset to their initial values.
1326
- */
1327
- clear() {
1328
- this._elements = [];
1329
- this._offset = 0;
1330
- }
1331
- /**
1332
- * Time Complexity: O(n)
1333
- * Space Complexity: O(1)
1334
- *
1335
- * The `compact` function in TypeScript slices the elements array based on the offset and resets the
1336
- * offset to zero.
1337
- * @returns The `compact()` method is returning a boolean value of `true`.
1338
- */
1339
- compact() {
1340
- this._elements = this.elements.slice(this.offset);
1341
- this._offset = 0;
1342
- return true;
1343
- }
1344
- /**
1345
- * Time Complexity: O(n)
1346
- * Space Complexity: O(n)
1347
- *
1348
- * The function overrides the splice method to remove and insert elements in a queue-like data
1349
- * structure.
1350
- * @param {number} start - The `start` parameter in the `splice` method specifies the index at which
1351
- * to start changing the array. Items will be added or removed starting from this index.
1352
- * @param {number} [deleteCount=0] - The `deleteCount` parameter in the `splice` method specifies the
1353
- * number of elements to remove from the array starting at the specified `start` index. If
1354
- * `deleteCount` is not provided, it defaults to 0, meaning no elements will be removed but new
1355
- * elements can still be inserted at
1356
- * @param {E[]} items - The `items` parameter in the `splice` method represents the elements that
1357
- * will be added to the array at the specified `start` index. These elements will replace the
1358
- * existing elements starting from the `start` index for the `deleteCount` number of elements.
1359
- * @returns The `splice` method is returning the `removedQueue`, which is an instance of the same
1360
- * class as the original object.
1361
- */
1362
- splice(start, deleteCount = 0, ...items) {
1363
- const removedQueue = this._createInstance();
1364
- start = Math.max(0, Math.min(start, this.length));
1365
- deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));
1366
- const globalStartIndex = this.offset + start;
1367
- const removedElements = this._elements.splice(globalStartIndex, deleteCount, ...items);
1368
- removedQueue.pushMany(removedElements);
1369
- this.compact();
1370
- return removedQueue;
1371
- }
1372
- /**
1373
- * Time Complexity: O(n)
1374
- * Space Complexity: O(n)
1375
- *
1376
- * The `clone()` function returns a new Queue object with the same elements as the original Queue.
1377
- * @returns The `clone()` method is returning a new instance of the `Queue` class.
1378
- */
1379
- clone() {
1380
- return new _Queue(this.elements.slice(this.offset), { toElementFn: this.toElementFn, maxLen: this._maxLen });
1381
- }
1382
- /**
1383
- * Time Complexity: O(n)
1384
- * Space Complexity: O(n)
1385
- *
1386
- * The `filter` function creates a new `Queue` object containing elements from the original `Queue`
1387
- * that satisfy a given predicate function.
1388
- * @param predicate - The `predicate` parameter is a callback function that takes three arguments:
1389
- * the current element being iterated over, the index of the current element, and the queue itself.
1390
- * It should return a boolean value indicating whether the element should be included in the filtered
1391
- * queue or not.
1392
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that specifies the value
1393
- * to be used as `this` when executing the `predicate` function. If `thisArg` is provided, it will be
1394
- * passed as the `this` value to the `predicate` function. If `thisArg` is
1395
- * @returns The `filter` method is returning a new `Queue` object that contains the elements that
1396
- * satisfy the given predicate function.
1397
- */
1398
- filter(predicate, thisArg) {
1399
- const newDeque = this._createInstance({
1400
- toElementFn: this._toElementFn,
1401
- autoCompactRatio: this._autoCompactRatio,
1402
- maxLen: this._maxLen
1403
- });
1404
- let index = 0;
1405
- for (const el of this) {
1406
- if (predicate.call(thisArg, el, index, this)) {
1407
- newDeque.push(el);
1408
- }
1409
- index++;
1410
- }
1411
- return newDeque;
1412
- }
1413
- /**
1414
- * Time Complexity: O(n)
1415
- * Space Complexity: O(n)
1416
- *
1417
- * The `map` function in TypeScript creates a new Queue by applying a callback function to each
1418
- * element in the original Queue.
1419
- * @param callback - The `callback` parameter is a function that will be applied to each element in
1420
- * the queue. It takes the current element, its index, and the queue itself as arguments, and returns
1421
- * a new element.
1422
- * @param [toElementFn] - The `toElementFn` parameter is an optional function that can be provided to
1423
- * convert a raw element of type `RM` to a new element of type `EM`. This function is used within the
1424
- * `map` method to transform each raw element before passing it to the `callback` function. If
1425
- * @param {any} [thisArg] - The `thisArg` parameter in the `map` function is used to specify the
1426
- * value of `this` when executing the `callback` function. It allows you to set the context (the
1427
- * value of `this`) within the callback function. If `thisArg` is provided, it will be
1428
- * @returns A new Queue object containing elements of type EM, which are the result of applying the
1429
- * callback function to each element in the original Queue object.
1430
- */
1431
- map(callback, toElementFn, thisArg) {
1432
- const newDeque = new _Queue([], {
1433
- toElementFn,
1434
- autoCompactRatio: this._autoCompactRatio,
1435
- maxLen: this._maxLen
1436
- });
1437
- let index = 0;
1438
- for (const el of this) {
1439
- newDeque.push(callback.call(thisArg, el, index, this));
1440
- index++;
1441
- }
1442
- return newDeque;
1443
- }
1444
- /**
1445
- * Time Complexity: O(n)
1446
- * Space Complexity: O(n)
1447
- *
1448
- * The function `_getIterator` returns an iterable iterator for the elements in the class.
1449
- */
1450
- *_getIterator() {
1451
- for (const item of this.elements.slice(this.offset)) {
1452
- yield item;
1453
- }
1454
- }
1455
- /**
1456
- * The function `_createInstance` returns a new instance of the `Queue` class with the specified
1457
- * options.
1458
- * @param [options] - The `options` parameter in the `_createInstance` method is of type
1459
- * `QueueOptions<E, R>`, which is used to configure the behavior of the queue being created. It
1460
- * allows you to specify settings or properties that can influence how the queue operates.
1461
- * @returns An instance of the `Queue` class with an empty array and the provided options is being
1462
- * returned.
1463
- */
1464
- _createInstance(options) {
1465
- return new _Queue([], options);
1466
- }
1467
- /**
1468
- * The function `_getReverseIterator` returns an iterator that iterates over elements in reverse
1469
- * order.
1470
- */
1471
- *_getReverseIterator() {
1472
- for (let i = this.length - 1; i >= 0; i--) {
1473
- const cur = this.at(i);
1474
- if (cur !== void 0) yield cur;
1475
- }
1476
- }
1477
- };
1478
-
1479
- // src/data-structures/graph/abstract-graph.ts
1480
- var AbstractVertex = class {
1481
- key;
1482
- value;
1483
- /**
1484
- * The function is a protected constructor that takes an key and an optional value as parameters.
1485
- * @param {VertexKey} key - The `key` parameter is of type `VertexKey` and represents the identifier of the vertex. It is
1486
- * used to uniquely identify the vertex object.
1487
- * @param {V} [value] - The parameter "value" is an optional parameter of type V. It is used to assign a value to the
1488
- * vertex. If no value is provided, it will be set to undefined.
1489
- */
1490
- constructor(key, value) {
1491
- this.key = key;
1492
- this.value = value;
1493
- }
1494
- };
1495
- var AbstractEdge = class {
1496
- value;
1497
- weight;
1498
- /**
1499
- * The above function is a protected constructor that initializes the weight, value, and hash code properties of an
1500
- * object.
1501
- * @param {number} [weight] - The `weight` parameter is an optional number that represents the weight of the object. If
1502
- * a value is provided, it will be assigned to the `_weight` property. If no value is provided, the default value of 1
1503
- * will be assigned.
1504
- * @param {VO} [value] - The `value` parameter is of type `VO`, which means it can be any type. It is an optional parameter,
1505
- * meaning it can be omitted when creating an instance of the class.
1506
- */
1507
- constructor(weight, value) {
1508
- this.weight = weight !== void 0 ? weight : 1;
1509
- this.value = value;
1510
- this._hashCode = uuidV4();
1511
- }
1512
- _hashCode;
1513
- get hashCode() {
1514
- return this._hashCode;
1515
- }
1516
- /**
1517
- * In TypeScript, a subclass inherits the interface implementation of its parent class, without needing to implement the same interface again in the subclass. This behavior differs from Java's approach. In Java, if a parent class implements an interface, the subclass needs to explicitly implement the same interface, even if the parent class has already implemented it.
1518
- * This means that using abstract methods in the parent class cannot constrain the grandchild classes. Defining methods within an interface also cannot constrain the descendant classes. When inheriting from this class, developers need to be aware that this method needs to be overridden.
1519
- */
1520
- };
1521
- var AbstractGraph = class extends IterableEntryBase {
1522
- constructor() {
1523
- super();
1524
- }
1525
- _vertexMap = /* @__PURE__ */ new Map();
1526
- get vertexMap() {
1527
- return this._vertexMap;
1528
- }
1529
- set vertexMap(v) {
1530
- this._vertexMap = v;
1531
- }
1532
- get size() {
1533
- return this._vertexMap.size;
1534
- }
1535
- /**
1536
- * Time Complexity: O(1) - Constant time for Map lookup.
1537
- * Space Complexity: O(1) - Constant space, as it creates only a few variables.
1538
- *
1539
- * The function "getVertex" returns the vertex with the specified ID or undefined if it doesn't exist.
1540
- * @param {VertexKey} vertexKey - The `vertexKey` parameter is the identifier of the vertex that you want to retrieve from
1541
- * the `_vertexMap` map.
1542
- * @returns The method `getVertex` returns the vertex with the specified `vertexKey` if it exists in the `_vertexMap`
1543
- * map. If the vertex does not exist, it returns `undefined`.
1544
- */
1545
- getVertex(vertexKey) {
1546
- return this._vertexMap.get(vertexKey) || void 0;
1547
- }
1548
- /**
1549
- * Time Complexity: O(1) - Constant time for Map lookup.
1550
- * Space Complexity: O(1) - Constant space, as it creates only a few variables.
1551
- *
1552
- * The function checks if a vertex exists in a graph.
1553
- * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID
1554
- * (`VertexKey`).
1555
- * @returns a boolean value.
1556
- */
1557
- hasVertex(vertexOrKey) {
1558
- return this._vertexMap.has(this._getVertexKey(vertexOrKey));
1559
- }
1560
- /**
1561
- * Time Complexity: O(1) - Constant time for Map operations.
1562
- * Space Complexity: O(1) - Constant space, as it creates only a few variables.
1563
- */
1564
- addVertex(keyOrVertex, value) {
1565
- if (keyOrVertex instanceof AbstractVertex) {
1566
- return this._addVertex(keyOrVertex);
1567
- } else {
1568
- const newVertex = this.createVertex(keyOrVertex, value);
1569
- return this._addVertex(newVertex);
1570
- }
1571
- }
1572
- isVertexKey(potentialKey) {
1573
- const potentialKeyType = typeof potentialKey;
1574
- return potentialKeyType === "string" || potentialKeyType === "number";
1575
- }
1576
- /**
1577
- * Time Complexity: O(K), where K is the number of vertexMap to be removed.
1578
- * Space Complexity: O(1) - Constant space, as it creates only a few variables.
1579
- *
1580
- * The function removes all vertexMap from a graph and returns a boolean indicating if any vertexMap were removed.
1581
- * @param {VO[] | VertexKey[]} vertexMap - The `vertexMap` parameter can be either an array of vertexMap (`VO[]`) or an array
1582
- * of vertex IDs (`VertexKey[]`).
1583
- * @returns a boolean value. It returns true if at least one vertex was successfully removed, and false if no vertexMap
1584
- * were removed.
1585
- */
1586
- removeManyVertices(vertexMap) {
1587
- const removed = [];
1588
- for (const v of vertexMap) {
1589
- removed.push(this.deleteVertex(v));
1590
- }
1591
- return removed.length > 0;
1592
- }
1593
- /**
1594
- * Time Complexity: O(1) - Depends on the implementation in the concrete class.
1595
- * Space Complexity: O(1) - Depends on the implementation in the concrete class.
1596
- *
1597
- * The function checks if there is an edge between two vertexMap and returns a boolean value indicating the result.
1598
- * @param {VertexKey | VO} v1 - The parameter v1 can be either a VertexKey or a VO. A VertexKey represents the unique
1599
- * identifier of a vertex in a graph, while VO represents the type of the vertex object itself.
1600
- * @param {VertexKey | VO} v2 - The parameter `v2` represents the second vertex in the edge. It can be either a
1601
- * `VertexKey` or a `VO` type, which represents the type of the vertex.
1602
- * @returns A boolean value is being returned.
1603
- */
1604
- hasEdge(v1, v2) {
1605
- const edge = this.getEdge(v1, v2);
1606
- return !!edge;
1607
- }
1608
- /**
1609
- * Time Complexity: O(1) - Depends on the implementation in the concrete class.
1610
- * Space Complexity: O(1) - Depends on the implementation in the concrete class.
1611
- */
1612
- addEdge(srcOrEdge, dest, weight, value) {
1613
- if (srcOrEdge instanceof AbstractEdge) {
1614
- return this._addEdge(srcOrEdge);
1615
- } else {
1616
- if (dest instanceof AbstractVertex || typeof dest === "string" || typeof dest === "number") {
1617
- if (!(this.hasVertex(srcOrEdge) && this.hasVertex(dest))) return false;
1618
- if (srcOrEdge instanceof AbstractVertex) srcOrEdge = srcOrEdge.key;
1619
- if (dest instanceof AbstractVertex) dest = dest.key;
1620
- const newEdge = this.createEdge(srcOrEdge, dest, weight, value);
1621
- return this._addEdge(newEdge);
1622
- } else {
1623
- throw new Error("dest must be a Vertex or vertex key while srcOrEdge is an Edge");
1624
- }
1625
- }
1626
- }
1627
- /**
1628
- * Time Complexity: O(1) - Constant time for Map and Edge operations.
1629
- * Space Complexity: O(1) - Constant space, as it creates only a few variables.
1630
- *
1631
- * The function sets the weight of an edge between two vertexMap in a graph.
1632
- * @param {VertexKey | VO} srcOrKey - The `srcOrKey` parameter can be either a `VertexKey` or a `VO` object. It represents
1633
- * the source vertex of the edge.
1634
- * @param {VertexKey | VO} destOrKey - The `destOrKey` parameter represents the destination vertex of the edge. It can be
1635
- * either a `VertexKey` or a vertex object `VO`.
1636
- * @param {number} weight - The weight parameter represents the weight of the edge between the source vertex (srcOrKey)
1637
- * and the destination vertex (destOrKey).
1638
- * @returns a boolean value. If the edge exists between the source and destination vertexMap, the function will update
1639
- * the weight of the edge and return true. If the edge does not exist, the function will return false.
1640
- */
1641
- setEdgeWeight(srcOrKey, destOrKey, weight) {
1642
- const edge = this.getEdge(srcOrKey, destOrKey);
1643
- if (edge) {
1644
- edge.weight = weight;
1645
- return true;
1646
- } else {
1647
- return false;
1648
- }
1649
- }
1650
- /**
1651
- * Time Complexity: O(P), where P is the number of paths found (in the worst case, exploring all paths).
1652
- * Space Complexity: O(P) - Linear space, where P is the number of paths found.
1653
- *
1654
- * The function `getAllPathsBetween` finds all paths between two vertexMap in a graph using depth-first search.
1655
- * @param {VO | VertexKey} v1 - The parameter `v1` represents either a vertex object (`VO`) or a vertex ID (`VertexKey`).
1656
- * It is the starting vertex for finding paths.
1657
- * @param {VO | VertexKey} v2 - The parameter `v2` represents either a vertex object (`VO`) or a vertex ID (`VertexKey`).
1658
- * @param limit - The count of limitation of result array.
1659
- * @returns The function `getAllPathsBetween` returns an array of arrays of vertexMap (`VO[][]`).
1660
- */
1661
- getAllPathsBetween(v1, v2, limit = 1e3) {
1662
- const paths = [];
1663
- const vertex1 = this._getVertex(v1);
1664
- const vertex2 = this._getVertex(v2);
1665
- if (!(vertex1 && vertex2)) {
1666
- return [];
1667
- }
1668
- const stack = [];
1669
- stack.push({ vertex: vertex1, path: [vertex1] });
1670
- while (stack.length > 0) {
1671
- const { vertex, path } = stack.pop();
1672
- if (vertex === vertex2) {
1673
- paths.push(path);
1674
- if (paths.length >= limit) return paths;
1675
- }
1676
- const neighbors = this.getNeighbors(vertex);
1677
- for (const neighbor of neighbors) {
1678
- if (!path.includes(neighbor)) {
1679
- const newPath = [...path, neighbor];
1680
- stack.push({ vertex: neighbor, path: newPath });
1681
- }
1682
- }
1683
- }
1684
- return paths;
1685
- }
1686
- /**
1687
- * Time Complexity: O(L), where L is the length of the path.
1688
- * Space Complexity: O(1) - Constant space.
1689
- *
1690
- * The function calculates the sum of weights along a given path.
1691
- * @param {VO[]} path - An array of vertexMap (VO) representing a path in a graph.
1692
- * @returns The function `getPathSumWeight` returns the sum of the weights of the edgeMap in the given path.
1693
- */
1694
- getPathSumWeight(path) {
1695
- let sum = 0;
1696
- for (let i = 0; i < path.length; i++) {
1697
- sum += this.getEdge(path[i], path[i + 1])?.weight || 0;
1698
- }
1699
- return sum;
1700
- }
1701
- /**
1702
- * Time Complexity: O(V + E) - Depends on the implementation (Dijkstra's algorithm).
1703
- * Space Complexity: O(V + E) - Depends on the implementation (Dijkstra's algorithm).
1704
- *
1705
- * The function `getMinCostBetween` calculates the minimum cost between two vertexMap in a graph, either based on edge
1706
- * weights or using a breadth-first search algorithm.
1707
- * @param {VO | VertexKey} v1 - The parameter `v1` represents the starting vertex or its ID.
1708
- * @param {VO | VertexKey} v2 - The parameter `v2` represents the destination vertex or its ID. It is the vertex to which
1709
- * you want to find the minimum cost or weight from the source vertex `v1`.
1710
- * @param {boolean} [isWeight] - isWeight is an optional parameter that indicates whether the graph edgeMap have weights.
1711
- * If isWeight is set to true, the function will calculate the minimum cost between v1 and v2 based on the weights of
1712
- * the edgeMap. If isWeight is set to false or not provided, the function will calculate the
1713
- * @returns The function `getMinCostBetween` returns a number representing the minimum cost between two vertexMap (`v1`
1714
- * and `v2`). If the `isWeight` parameter is `true`, it calculates the minimum weight among all paths between the
1715
- * vertexMap. If `isWeight` is `false` or not provided, it uses a breadth-first search (BFS) algorithm to calculate the
1716
- * minimum number of
1717
- */
1718
- getMinCostBetween(v1, v2, isWeight) {
1719
- if (isWeight === void 0) isWeight = false;
1720
- if (isWeight) {
1721
- const allPaths = this.getAllPathsBetween(v1, v2);
1722
- let min = Number.MAX_SAFE_INTEGER;
1723
- for (const path of allPaths) {
1724
- min = Math.min(this.getPathSumWeight(path), min);
1725
- }
1726
- return min;
1727
- } else {
1728
- const vertex2 = this._getVertex(v2);
1729
- const vertex1 = this._getVertex(v1);
1730
- if (!(vertex1 && vertex2)) {
1731
- return void 0;
1732
- }
1733
- const visited = /* @__PURE__ */ new Map();
1734
- const queue = new Queue([vertex1]);
1735
- visited.set(vertex1, true);
1736
- let cost = 0;
1737
- while (queue.length > 0) {
1738
- for (let i = 0; i < queue.length; i++) {
1739
- const cur = queue.shift();
1740
- if (cur === vertex2) {
1741
- return cost;
1742
- }
1743
- if (cur !== void 0) {
1744
- const neighbors = this.getNeighbors(cur);
1745
- for (const neighbor of neighbors) {
1746
- if (!visited.has(neighbor)) {
1747
- visited.set(neighbor, true);
1748
- queue.push(neighbor);
1749
- }
1750
- }
1751
- }
1752
- }
1753
- cost++;
1754
- }
1755
- return void 0;
1756
- }
1757
- }
1758
- /**
1759
- * Time Complexity: O(V + E) - Depends on the implementation (Dijkstra's algorithm or DFS).
1760
- * Space Complexity: O(V + E) - Depends on the implementation (Dijkstra's algorithm or DFS).
1761
- *
1762
- * The function `getMinPathBetween` returns the minimum path between two vertexMap in a graph, either based on weight or
1763
- * using a breadth-first search algorithm.
1764
- * @param {VO | VertexKey} v1 - The parameter `v1` represents the starting vertex of the path. It can be either a vertex
1765
- * object (`VO`) or a vertex ID (`VertexKey`).
1766
- * @param {VO | VertexKey} v2 - VO | VertexKey - The second vertex or vertex ID between which we want to find the minimum
1767
- * path.
1768
- * @param {boolean} [isWeight] - A boolean flag indicating whether to consider the weight of edgeMap in finding the
1769
- * minimum path. If set to true, the function will use Dijkstra's algorithm to find the minimum weighted path. If set
1770
- * to false, the function will use breadth-first search (BFS) to find the minimum path.
1771
- * @param isDFS - If set to true, it enforces the use of getAllPathsBetween to first obtain all possible paths,
1772
- * followed by iterative computation of the shortest path. This approach may result in exponential time complexity,
1773
- * so the default method is to use the Dijkstra algorithm to obtain the shortest weighted path.
1774
- * @returns The function `getMinPathBetween` returns an array of vertexMap (`VO[]`) representing the minimum path between
1775
- * two vertexMap (`v1` and `v2`). If there is no path between the vertexMap, it returns `undefined`.
1776
- */
1777
- getMinPathBetween(v1, v2, isWeight, isDFS = false) {
1778
- if (isWeight === void 0) isWeight = false;
1779
- if (isWeight) {
1780
- if (isDFS) {
1781
- const allPaths = this.getAllPathsBetween(v1, v2, 1e4);
1782
- let min = Number.MAX_SAFE_INTEGER;
1783
- let minIndex = -1;
1784
- let index = 0;
1785
- for (const path of allPaths) {
1786
- const pathSumWeight = this.getPathSumWeight(path);
1787
- if (pathSumWeight < min) {
1788
- min = pathSumWeight;
1789
- minIndex = index;
1790
- }
1791
- index++;
1792
- }
1793
- return allPaths[minIndex] || void 0;
1794
- } else {
1795
- return this.dijkstra(v1, v2, true, true)?.minPath ?? [];
1796
- }
1797
- } else {
1798
- let minPath = [];
1799
- const vertex1 = this._getVertex(v1);
1800
- const vertex2 = this._getVertex(v2);
1801
- if (!(vertex1 && vertex2)) return [];
1802
- const dfs = (cur, dest, visiting, path) => {
1803
- visiting.add(cur);
1804
- if (cur === dest) {
1805
- minPath = [vertex1, ...path];
1806
- return;
1807
- }
1808
- const neighbors = this.getNeighbors(cur);
1809
- for (const neighbor of neighbors) {
1810
- if (!visiting.has(neighbor)) {
1811
- path.push(neighbor);
1812
- dfs(neighbor, dest, visiting, path);
1813
- path.pop();
1814
- }
1815
- }
1816
- visiting.delete(cur);
1817
- };
1818
- dfs(vertex1, vertex2, /* @__PURE__ */ new Set(), []);
1819
- return minPath;
1820
- }
1821
- }
1822
- /**
1823
- * Time Complexity: O(V^2 + E) - Quadratic time in the worst case (no heap optimization).
1824
- * Space Complexity: O(V + E) - Depends on the implementation (Dijkstra's algorithm).
1825
- *
1826
- * The function `dijkstraWithoutHeap` implements Dijkstra's algorithm to find the shortest path between two vertexMap in
1827
- * a graph without using a heap data structure.
1828
- * @param {VO | VertexKey} src - The source vertex from which to start the Dijkstra's algorithm. It can be either a
1829
- * vertex object or a vertex ID.
1830
- * @param {VO | VertexKey | undefined} [dest] - The `dest` parameter in the `dijkstraWithoutHeap` function is an optional
1831
- * parameter that specifies the destination vertex for the Dijkstra algorithm. It can be either a vertex object or its
1832
- * identifier. If no destination is provided, the value is set to `undefined`.
1833
- * @param {boolean} [getMinDist] - The `getMinDist` parameter is a boolean flag that determines whether the minimum
1834
- * distance from the source vertex to the destination vertex should be calculated and returned in the result. If
1835
- * `getMinDist` is set to `true`, the `minDist` property in the result will contain the minimum distance
1836
- * @param {boolean} [genPaths] - The `genPaths` parameter is a boolean flag that determines whether or not to generate
1837
- * paths in the Dijkstra algorithm. If `genPaths` is set to `true`, the algorithm will calculate and return the
1838
- * shortest paths from the source vertex to all other vertexMap in the graph. If `genPaths
1839
- * @returns The function `dijkstraWithoutHeap` returns an object of type `DijkstraResult<VO>`.
1840
- */
1841
- dijkstraWithoutHeap(src, dest = void 0, getMinDist = false, genPaths = false) {
1842
- let minDist = Number.MAX_SAFE_INTEGER;
1843
- let minDest = void 0;
1844
- let minPath = [];
1845
- const paths = [];
1846
- const vertexMap = this._vertexMap;
1847
- const distMap = /* @__PURE__ */ new Map();
1848
- const seen = /* @__PURE__ */ new Set();
1849
- const preMap = /* @__PURE__ */ new Map();
1850
- const srcVertex = this._getVertex(src);
1851
- const destVertex = dest ? this._getVertex(dest) : void 0;
1852
- if (!srcVertex) {
1853
- return void 0;
1854
- }
1855
- for (const vertex of vertexMap) {
1856
- const vertexOrKey = vertex[1];
1857
- if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);
1858
- }
1859
- distMap.set(srcVertex, 0);
1860
- preMap.set(srcVertex, void 0);
1861
- const getMinOfNoSeen = () => {
1862
- let min = Number.MAX_SAFE_INTEGER;
1863
- let minV = void 0;
1864
- for (const [key, value] of distMap) {
1865
- if (!seen.has(key)) {
1866
- if (value < min) {
1867
- min = value;
1868
- minV = key;
1869
- }
1870
- }
1871
- }
1872
- return minV;
1873
- };
1874
- const getPaths = (minV) => {
1875
- for (const vertex of vertexMap) {
1876
- const vertexOrKey = vertex[1];
1877
- if (vertexOrKey instanceof AbstractVertex) {
1878
- const path = [vertexOrKey];
1879
- let parent = preMap.get(vertexOrKey);
1880
- while (parent) {
1881
- path.push(parent);
1882
- parent = preMap.get(parent);
1883
- }
1884
- const reversed = path.reverse();
1885
- if (vertex[1] === minV) minPath = reversed;
1886
- paths.push(reversed);
1887
- }
1888
- }
1889
- };
1890
- for (let i = 1; i < vertexMap.size; i++) {
1891
- const cur = getMinOfNoSeen();
1892
- if (cur) {
1893
- seen.add(cur);
1894
- if (destVertex && destVertex === cur) {
1895
- if (getMinDist) {
1896
- minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;
1897
- }
1898
- if (genPaths) {
1899
- getPaths(destVertex);
1900
- }
1901
- return { distMap, preMap, seen, paths, minDist, minPath };
1902
- }
1903
- const neighbors = this.getNeighbors(cur);
1904
- for (const neighbor of neighbors) {
1905
- if (!seen.has(neighbor)) {
1906
- const edge = this.getEdge(cur, neighbor);
1907
- if (edge) {
1908
- const curFromMap = distMap.get(cur);
1909
- const neighborFromMap = distMap.get(neighbor);
1910
- if (curFromMap !== void 0 && neighborFromMap !== void 0) {
1911
- if (edge.weight + curFromMap < neighborFromMap) {
1912
- distMap.set(neighbor, edge.weight + curFromMap);
1913
- preMap.set(neighbor, cur);
1914
- }
1915
- }
1916
- }
1917
- }
1918
- }
1919
- }
1920
- }
1921
- if (getMinDist)
1922
- distMap.forEach((d, v) => {
1923
- if (v !== srcVertex) {
1924
- if (d < minDist) {
1925
- minDist = d;
1926
- if (genPaths) minDest = v;
1927
- }
1928
- }
1929
- });
1930
- if (genPaths) getPaths(minDest);
1931
- return { distMap, preMap, seen, paths, minDist, minPath };
1932
- }
1933
- /**
1934
- * Time Complexity: O((V + E) * log(V)) - Depends on the implementation (using a binary heap).
1935
- * Space Complexity: O(V + E) - Depends on the implementation (using a binary heap).
1936
- *
1937
- * Dijkstra's algorithm is used to find the shortest paths from a source node to all other nodes in a graph. Its basic idea is to repeatedly choose the node closest to the source node and update the distances of other nodes using this node as an intermediary. Dijkstra's algorithm requires that the edge weights in the graph are non-negative.
1938
- * The `dijkstra` function implements Dijkstra's algorithm to find the shortest path between a source vertex and an
1939
- * optional destination vertex, and optionally returns the minimum distance, the paths, and other information.
1940
- * @param {VO | VertexKey} src - The `src` parameter represents the source vertex from which the Dijkstra algorithm will
1941
- * start. It can be either a vertex object or a vertex ID.
1942
- * @param {VO | VertexKey | undefined} [dest] - The `dest` parameter is the destination vertex or vertex ID. It specifies the
1943
- * vertex to which the shortest path is calculated from the source vertex. If no destination is provided, the algorithm
1944
- * will calculate the shortest paths to all other vertexMap from the source vertex.
1945
- * @param {boolean} [getMinDist] - The `getMinDist` parameter is a boolean flag that determines whether the minimum
1946
- * distance from the source vertex to the destination vertex should be calculated and returned in the result. If
1947
- * `getMinDist` is set to `true`, the `minDist` property in the result will contain the minimum distance
1948
- * @param {boolean} [genPaths] - The `genPaths` parameter is a boolean flag that determines whether or not to generate
1949
- * paths in the Dijkstra algorithm. If `genPaths` is set to `true`, the algorithm will calculate and return the
1950
- * shortest paths from the source vertex to all other vertexMap in the graph. If `genPaths
1951
- * @returns The function `dijkstra` returns an object of type `DijkstraResult<VO>`.
1952
- */
1953
- dijkstra(src, dest = void 0, getMinDist = false, genPaths = false) {
1954
- let minDist = Number.MAX_SAFE_INTEGER;
1955
- let minDest = void 0;
1956
- let minPath = [];
1957
- const paths = [];
1958
- const vertexMap = this._vertexMap;
1959
- const distMap = /* @__PURE__ */ new Map();
1960
- const seen = /* @__PURE__ */ new Set();
1961
- const preMap = /* @__PURE__ */ new Map();
1962
- const srcVertex = this._getVertex(src);
1963
- const destVertex = dest ? this._getVertex(dest) : void 0;
1964
- if (!srcVertex) return void 0;
1965
- for (const vertex of vertexMap) {
1966
- const vertexOrKey = vertex[1];
1967
- if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);
1968
- }
1969
- const heap = new Heap([], { comparator: (a, b) => a.key - b.key });
1970
- heap.add({ key: 0, value: srcVertex });
1971
- distMap.set(srcVertex, 0);
1972
- preMap.set(srcVertex, void 0);
1973
- const getPaths = (minV) => {
1974
- for (const vertex of vertexMap) {
1975
- const vertexOrKey = vertex[1];
1976
- if (vertexOrKey instanceof AbstractVertex) {
1977
- const path = [vertexOrKey];
1978
- let parent = preMap.get(vertexOrKey);
1979
- while (parent) {
1980
- path.push(parent);
1981
- parent = preMap.get(parent);
1982
- }
1983
- const reversed = path.reverse();
1984
- if (vertex[1] === minV) minPath = reversed;
1985
- paths.push(reversed);
1986
- }
1987
- }
1988
- };
1989
- while (heap.size > 0) {
1990
- const curHeapNode = heap.poll();
1991
- const dist = curHeapNode?.key;
1992
- const cur = curHeapNode?.value;
1993
- if (dist !== void 0) {
1994
- if (cur) {
1995
- seen.add(cur);
1996
- if (destVertex && destVertex === cur) {
1997
- if (getMinDist) {
1998
- minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;
1999
- }
2000
- if (genPaths) {
2001
- getPaths(destVertex);
2002
- }
2003
- return { distMap, preMap, seen, paths, minDist, minPath };
2004
- }
2005
- const neighbors = this.getNeighbors(cur);
2006
- for (const neighbor of neighbors) {
2007
- if (!seen.has(neighbor)) {
2008
- const weight = this.getEdge(cur, neighbor)?.weight;
2009
- if (typeof weight === "number") {
2010
- const distSrcToNeighbor = distMap.get(neighbor);
2011
- if (distSrcToNeighbor) {
2012
- if (dist + weight < distSrcToNeighbor) {
2013
- heap.add({ key: dist + weight, value: neighbor });
2014
- preMap.set(neighbor, cur);
2015
- distMap.set(neighbor, dist + weight);
2016
- }
2017
- }
2018
- }
2019
- }
2020
- }
2021
- }
2022
- }
2023
- }
2024
- if (getMinDist) {
2025
- distMap.forEach((d, v) => {
2026
- if (v !== srcVertex) {
2027
- if (d < minDist) {
2028
- minDist = d;
2029
- if (genPaths) minDest = v;
2030
- }
2031
- }
2032
- });
2033
- }
2034
- if (genPaths) {
2035
- getPaths(minDest);
2036
- }
2037
- return { distMap, preMap, seen, paths, minDist, minPath };
2038
- }
2039
- /**
2040
- * Time Complexity: O(V * E) - Quadratic time in the worst case (Bellman-Ford algorithm).
2041
- * Space Complexity: O(V + E) - Depends on the implementation (Bellman-Ford algorithm).
2042
- *
2043
- * one to rest pairs
2044
- * The Bellman-Ford algorithm is also used to find the shortest paths from a source node to all other nodes in a graph. Unlike Dijkstra's algorithm, it can handle edge weights that are negative. Its basic idea involves iterative relaxation of all edgeMap for several rounds to gradually approximate the shortest paths. Due to its ability to handle negative-weight edgeMap, the Bellman-Ford algorithm is more flexible in some scenarios.
2045
- * The `bellmanFord` function implements the Bellman-Ford algorithm to find the shortest path from a source vertex to
2046
- * all other vertexMap in a graph, and optionally detects negative cycles and generates the minimum path.
2047
- * @param {VO | VertexKey} src - The `src` parameter is the source vertex from which the Bellman-Ford algorithm will
2048
- * start calculating the shortest paths. It can be either a vertex object or a vertex ID.
2049
- * @param {boolean} [scanNegativeCycle] - A boolean flag indicating whether to scan for negative cycles in the graph.
2050
- * @param {boolean} [getMin] - The `getMin` parameter is a boolean flag that determines whether the algorithm should
2051
- * calculate the minimum distance from the source vertex to all other vertexMap in the graph. If `getMin` is set to
2052
- * `true`, the algorithm will find the minimum distance and update the `min` variable with the minimum
2053
- * @param {boolean} [genPath] - A boolean flag indicating whether to generate paths for all vertexMap from the source
2054
- * vertex.
2055
- * @returns The function `bellmanFord` returns an object with the following properties:
2056
- */
2057
- bellmanFord(src, scanNegativeCycle, getMin, genPath) {
2058
- if (getMin === void 0) getMin = false;
2059
- if (genPath === void 0) genPath = false;
2060
- const srcVertex = this._getVertex(src);
2061
- const paths = [];
2062
- const distMap = /* @__PURE__ */ new Map();
2063
- const preMap = /* @__PURE__ */ new Map();
2064
- let min = Number.MAX_SAFE_INTEGER;
2065
- let minPath = [];
2066
- let hasNegativeCycle;
2067
- if (scanNegativeCycle) hasNegativeCycle = false;
2068
- if (!srcVertex) return { hasNegativeCycle, distMap, preMap, paths, min, minPath };
2069
- const vertexMap = this._vertexMap;
2070
- const numOfVertices = vertexMap.size;
2071
- const edgeMap = this.edgeSet();
2072
- const numOfEdges = edgeMap.length;
2073
- this._vertexMap.forEach((vertex) => {
2074
- distMap.set(vertex, Number.MAX_SAFE_INTEGER);
2075
- });
2076
- distMap.set(srcVertex, 0);
2077
- for (let i = 1; i < numOfVertices; ++i) {
2078
- for (let j = 0; j < numOfEdges; ++j) {
2079
- const ends = this.getEndsOfEdge(edgeMap[j]);
2080
- if (ends) {
2081
- const [s, d] = ends;
2082
- const weight = edgeMap[j].weight;
2083
- const sWeight = distMap.get(s);
2084
- const dWeight = distMap.get(d);
2085
- if (sWeight !== void 0 && dWeight !== void 0) {
2086
- if (distMap.get(s) !== Number.MAX_SAFE_INTEGER && sWeight + weight < dWeight) {
2087
- distMap.set(d, sWeight + weight);
2088
- if (genPath) preMap.set(d, s);
2089
- }
2090
- }
2091
- }
2092
- }
2093
- }
2094
- let minDest = void 0;
2095
- if (getMin) {
2096
- distMap.forEach((d, v) => {
2097
- if (v !== srcVertex) {
2098
- if (d < min) {
2099
- min = d;
2100
- if (genPath) minDest = v;
2101
- }
2102
- }
2103
- });
2104
- }
2105
- if (genPath) {
2106
- for (const vertex of vertexMap) {
2107
- const vertexOrKey = vertex[1];
2108
- if (vertexOrKey instanceof AbstractVertex) {
2109
- const path = [vertexOrKey];
2110
- let parent = preMap.get(vertexOrKey);
2111
- while (parent !== void 0) {
2112
- path.push(parent);
2113
- parent = preMap.get(parent);
2114
- }
2115
- const reversed = path.reverse();
2116
- if (vertex[1] === minDest) minPath = reversed;
2117
- paths.push(reversed);
2118
- }
2119
- }
2120
- }
2121
- for (let j = 0; j < numOfEdges; ++j) {
2122
- const ends = this.getEndsOfEdge(edgeMap[j]);
2123
- if (ends) {
2124
- const [s] = ends;
2125
- const weight = edgeMap[j].weight;
2126
- const sWeight = distMap.get(s);
2127
- if (sWeight) {
2128
- if (sWeight !== Number.MAX_SAFE_INTEGER && sWeight + weight < sWeight) hasNegativeCycle = true;
2129
- }
2130
- }
2131
- }
2132
- return { hasNegativeCycle, distMap, preMap, paths, min, minPath };
2133
- }
2134
- /**
2135
- * Dijkstra algorithm time: O(logVE) space: O(VO + EO)
2136
- */
2137
- /**
2138
- * Dijkstra algorithm time: O(logVE) space: O(VO + EO)
2139
- * Dijkstra's algorithm is used to find the shortest paths from a source node to all other nodes in a graph. Its basic idea is to repeatedly choose the node closest to the source node and update the distances of other nodes using this node as an intermediary. Dijkstra's algorithm requires that the edge weights in the graph are non-negative.
2140
- */
2141
- /**
2142
- * BellmanFord time:O(VE) space:O(VO)
2143
- * one to rest pairs
2144
- * The Bellman-Ford algorithm is also used to find the shortest paths from a source node to all other nodes in a graph. Unlike Dijkstra's algorithm, it can handle edge weights that are negative. Its basic idea involves iterative relaxation of all edgeMap for several rounds to gradually approximate the shortest paths. Due to its ability to handle negative-weight edgeMap, the Bellman-Ford algorithm is more flexible in some scenarios.
2145
- * The `bellmanFord` function implements the Bellman-Ford algorithm to find the shortest path from a source vertex to
2146
- */
2147
- /**
2148
- * Time Complexity: O(V^3) - Cubic time (Floyd-Warshall algorithm).
2149
- * Space Complexity: O(V^2) - Quadratic space (Floyd-Warshall algorithm).
2150
- *
2151
- * Not support graph with negative weight cycle
2152
- * all pairs
2153
- * The Floyd-Warshall algorithm is used to find the shortest paths between all pairs of nodes in a graph. It employs dynamic programming to compute the shortest paths from any node to any other node. The Floyd-Warshall algorithm's advantage lies in its ability to handle graphs with negative-weight edgeMap, and it can simultaneously compute shortest paths between any two nodes.
2154
- * The function implements the Floyd-Warshall algorithm to find the shortest path between all pairs of vertexMap in a
2155
- * graph.
2156
- * @returns The function `floydWarshall()` returns an object with two properties: `costs` and `predecessor`. The `costs`
2157
- * property is a 2D array of numbers representing the shortest path costs between vertexMap in a graph. The
2158
- * `predecessor` property is a 2D array of vertexMap (or `undefined`) representing the predecessor vertexMap in the shortest
2159
- * path between vertexMap in the
2160
- */
2161
- floydWarshall() {
2162
- const idAndVertices = [...this._vertexMap];
2163
- const n = idAndVertices.length;
2164
- const costs = [];
2165
- const predecessor = [];
2166
- for (let i = 0; i < n; i++) {
2167
- costs[i] = [];
2168
- predecessor[i] = [];
2169
- for (let j = 0; j < n; j++) {
2170
- predecessor[i][j] = void 0;
2171
- }
2172
- }
2173
- for (let i = 0; i < n; i++) {
2174
- for (let j = 0; j < n; j++) {
2175
- costs[i][j] = this.getEdge(idAndVertices[i][1], idAndVertices[j][1])?.weight || Number.MAX_SAFE_INTEGER;
2176
- }
2177
- }
2178
- for (let k = 0; k < n; k++) {
2179
- for (let i = 0; i < n; i++) {
2180
- for (let j = 0; j < n; j++) {
2181
- if (costs[i][j] > costs[i][k] + costs[k][j]) {
2182
- costs[i][j] = costs[i][k] + costs[k][j];
2183
- predecessor[i][j] = idAndVertices[k][1];
2184
- }
2185
- }
2186
- }
2187
- }
2188
- return { costs, predecessor };
2189
- }
2190
- /**
2191
- * O(V+E+C)
2192
- * O(V+C)
2193
- */
2194
- getCycles(isInclude2Cycle = false) {
2195
- const cycles = [];
2196
- const visited = /* @__PURE__ */ new Set();
2197
- const dfs = (vertex, currentPath, visited2) => {
2198
- if (visited2.has(vertex)) {
2199
- if ((!isInclude2Cycle && currentPath.length > 2 || isInclude2Cycle && currentPath.length >= 2) && currentPath[0] === vertex.key) {
2200
- cycles.push([...currentPath]);
2201
- }
2202
- return;
2203
- }
2204
- visited2.add(vertex);
2205
- currentPath.push(vertex.key);
2206
- for (const neighbor of this.getNeighbors(vertex)) {
2207
- if (neighbor) dfs(neighbor, currentPath, visited2);
2208
- }
2209
- visited2.delete(vertex);
2210
- currentPath.pop();
2211
- };
2212
- for (const vertex of this.vertexMap.values()) {
2213
- dfs(vertex, [], visited);
2214
- }
2215
- const uniqueCycles = /* @__PURE__ */ new Map();
2216
- for (const cycle of cycles) {
2217
- const sorted = [...cycle].sort().toString();
2218
- if (uniqueCycles.has(sorted)) continue;
2219
- else {
2220
- uniqueCycles.set(sorted, cycle);
2221
- }
2222
- }
2223
- return [...uniqueCycles].map((cycleString) => cycleString[1]);
2224
- }
2225
- /**
2226
- * Time Complexity: O(n)
2227
- * Space Complexity: O(n)
2228
- *
2229
- * The `filter` function iterates over key-value pairs in a data structure and returns an array of
2230
- * pairs that satisfy a given predicate.
2231
- * @param predicate - The `predicate` parameter is a callback function that takes four arguments:
2232
- * `value`, `key`, `index`, and `this`. It is used to determine whether an element should be included
2233
- * in the filtered array. The callback function should return `true` if the element should be
2234
- * included, and `
2235
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that allows you to
2236
- * specify the value of `this` within the `predicate` function. It is used when you want to bind a
2237
- * specific object as the context for the `predicate` function. If `thisArg` is provided, it will be
2238
- * @returns The `filter` method returns an array of key-value pairs `[VertexKey, V | undefined][]`
2239
- * that satisfy the given predicate function.
2240
- */
2241
- filter(predicate, thisArg) {
2242
- const filtered = [];
2243
- let index = 0;
2244
- for (const [key, value] of this) {
2245
- if (predicate.call(thisArg, key, value, index, this)) {
2246
- filtered.push([key, value]);
2247
- }
2248
- index++;
2249
- }
2250
- return filtered;
2251
- }
2252
- /**
2253
- * Time Complexity: O(n)
2254
- * Space Complexity: O(n)
2255
- *
2256
- * The `map` function iterates over the elements of a collection and applies a callback function to
2257
- * each element, returning an array of the results.
2258
- * @param callback - The callback parameter is a function that will be called for each element in the
2259
- * map. It takes four arguments:
2260
- * @param {any} [thisArg] - The `thisArg` parameter is an optional argument that allows you to
2261
- * specify the value of `this` within the callback function. If `thisArg` is provided, it will be
2262
- * used as the `this` value when calling the callback function. If `thisArg` is not provided, `
2263
- * @returns The `map` function is returning an array of type `T[]`.
2264
- */
2265
- map(callback, thisArg) {
2266
- const mapped = [];
2267
- let index = 0;
2268
- for (const [key, value] of this) {
2269
- mapped.push(callback.call(thisArg, key, value, index, this));
2270
- index++;
2271
- }
2272
- return mapped;
2273
- }
2274
- *_getIterator() {
2275
- for (const vertex of this._vertexMap.values()) {
2276
- yield [vertex.key, vertex.value];
2277
- }
2278
- }
2279
- _addVertex(newVertex) {
2280
- if (this.hasVertex(newVertex)) {
2281
- return false;
2282
- }
2283
- this._vertexMap.set(newVertex.key, newVertex);
2284
- return true;
2285
- }
2286
- _getVertex(vertexOrKey) {
2287
- const vertexKey = this._getVertexKey(vertexOrKey);
2288
- return this._vertexMap.get(vertexKey) || void 0;
2289
- }
2290
- _getVertexKey(vertexOrKey) {
2291
- return vertexOrKey instanceof AbstractVertex ? vertexOrKey.key : vertexOrKey;
2292
- }
2293
- };
2294
-
2295
- // src/data-structures/graph/directed-graph.ts
2296
- var DirectedVertex = class extends AbstractVertex {
2297
- /**
2298
- * The constructor function initializes a vertex with an optional value.
2299
- * @param {VertexKey} key - The `key` parameter is of type `VertexKey` and represents the identifier of the vertex. It is
2300
- * used to uniquely identify the vertex within a graph or data structure.
2301
- * @param {V} [value] - The "value" parameter is an optional parameter of type V. It is used to initialize the value of the
2302
- * vertex. If no value is provided, the vertex will be initialized with a default value.
2303
- */
2304
- constructor(key, value) {
2305
- super(key, value);
2306
- }
2307
- };
2308
- var DirectedEdge = class extends AbstractEdge {
2309
- src;
2310
- dest;
2311
- /**
2312
- * The constructor function initializes the source and destination vertexMap of an edge, along with an optional weight
2313
- * and value.
2314
- * @param {VertexKey} src - The `src` parameter is the source vertex ID. It represents the starting point of an edge in
2315
- * a graph.
2316
- * @param {VertexKey} dest - The `dest` parameter represents the destination vertex of an edge. It is of type
2317
- * `VertexKey`, which is likely a unique identifier for a vertex in a graph.
2318
- * @param {number} [weight] - The weight parameter is an optional number that represents the weight of the edge.
2319
- * @param {E} [value] - The `value` parameter is an optional parameter of type `E`. It represents the value associated with
2320
- * the edge.
2321
- */
2322
- constructor(src, dest, weight, value) {
2323
- super(weight, value);
2324
- this.src = src;
2325
- this.dest = dest;
2326
- }
2327
- };
2328
- var DirectedGraph = class _DirectedGraph extends AbstractGraph {
2329
- /**
2330
- * The constructor function initializes an instance of a class.
2331
- */
2332
- constructor() {
2333
- super();
2334
- }
2335
- _outEdgeMap = /* @__PURE__ */ new Map();
2336
- get outEdgeMap() {
2337
- return this._outEdgeMap;
2338
- }
2339
- set outEdgeMap(v) {
2340
- this._outEdgeMap = v;
2341
- }
2342
- _inEdgeMap = /* @__PURE__ */ new Map();
2343
- get inEdgeMap() {
2344
- return this._inEdgeMap;
2345
- }
2346
- set inEdgeMap(v) {
2347
- this._inEdgeMap = v;
2348
- }
2349
- /**
2350
- * The function creates a new vertex with an optional value and returns it.
2351
- * @param {VertexKey} key - The `key` parameter is the unique identifier for the vertex. It is of type `VertexKey`, which
2352
- * could be a number or a string depending on how you want to identify your vertexMap.
2353
- * @param [value] - The 'value' parameter is an optional value that can be assigned to the vertex. If a value is provided,
2354
- * it will be assigned to the 'value' property of the vertex. If no value is provided, the 'value' property will be
2355
- * assigned the same value as the 'key' parameter
2356
- * @returns a new instance of a DirectedVertex object, casted as type VO.
2357
- */
2358
- createVertex(key, value) {
2359
- return new DirectedVertex(key, value);
2360
- }
2361
- /**
2362
- * The function creates a directed edge between two vertexMap with an optional weight and value.
2363
- * @param {VertexKey} src - The source vertex ID of the edge. It represents the starting point of the edge.
2364
- * @param {VertexKey} dest - The `dest` parameter is the identifier of the destination vertex for the edge.
2365
- * @param {number} [weight] - The weight parameter is an optional number that represents the weight of the edge. If no
2366
- * weight is provided, it defaults to 1.
2367
- * @param [value] - The 'value' parameter is an optional value that can be assigned to the edge. It can be of any type and
2368
- * is used to store additional information or data associated with the edge.
2369
- * @returns a new instance of a DirectedEdge object, casted as type EO.
2370
- */
2371
- createEdge(src, dest, weight, value) {
2372
- return new DirectedEdge(src, dest, weight ?? 1, value);
2373
- }
2374
- /**
2375
- * Time Complexity: O(|V|) where |V| is the number of vertexMap
2376
- * Space Complexity: O(1)
2377
- *
2378
- * The `getEdge` function retrieves an edge between two vertexMap based on their source and destination IDs.
2379
- * @param {VO | VertexKey | undefined} srcOrKey - The source vertex or its ID. It can be either a vertex object or a vertex ID.
2380
- * @param {VO | VertexKey | undefined} destOrKey - The `destOrKey` parameter in the `getEdge` function represents the
2381
- * destination vertex of the edge. It can be either a vertex object (`VO`), a vertex ID (`VertexKey`), or `undefined` if the
2382
- * destination is not specified.
2383
- * @returns the first edge found between the source and destination vertexMap, or undefined if no such edge is found.
2384
- */
2385
- getEdge(srcOrKey, destOrKey) {
2386
- let edgeMap = [];
2387
- if (srcOrKey !== void 0 && destOrKey !== void 0) {
2388
- const src = this._getVertex(srcOrKey);
2389
- const dest = this._getVertex(destOrKey);
2390
- if (src && dest) {
2391
- const srcOutEdges = this._outEdgeMap.get(src);
2392
- if (srcOutEdges) {
2393
- edgeMap = srcOutEdges.filter((edge) => edge.dest === dest.key);
2394
- }
2395
- }
2396
- }
2397
- return edgeMap[0] || void 0;
2398
- }
2399
- /**
2400
- * Time Complexity: O(|E|) where |E| is the number of edgeMap
2401
- * Space Complexity: O(1)
2402
- *
2403
- * The function removes an edge between two vertexMap in a graph and returns the removed edge.
2404
- * @param {VO | VertexKey} srcOrKey - The source vertex or its ID.
2405
- * @param {VO | VertexKey} destOrKey - The `destOrKey` parameter represents the destination vertex or its ID.
2406
- * @returns the removed edge (EO) if it exists, or undefined if either the source or destination vertex does not exist.
2407
- */
2408
- deleteEdgeSrcToDest(srcOrKey, destOrKey) {
2409
- const src = this._getVertex(srcOrKey);
2410
- const dest = this._getVertex(destOrKey);
2411
- let removed = void 0;
2412
- if (!src || !dest) {
2413
- return void 0;
2414
- }
2415
- const srcOutEdges = this._outEdgeMap.get(src);
2416
- if (srcOutEdges) {
2417
- arrayRemove(srcOutEdges, (edge) => edge.dest === dest.key);
2418
- }
2419
- const destInEdges = this._inEdgeMap.get(dest);
2420
- if (destInEdges) {
2421
- removed = arrayRemove(destInEdges, (edge) => edge.src === src.key)[0] || void 0;
2422
- }
2423
- return removed;
2424
- }
2425
- /**
2426
- * Time Complexity: O(E) where E is the number of edgeMap
2427
- * Space Complexity: O(1)
2428
- *
2429
- * The `deleteEdge` function removes an edge from a graph and returns the removed edge.
2430
- * @param {EO | VertexKey} edgeOrSrcVertexKey - The `edge` parameter can be either an `EO` object (edge object) or
2431
- * a `VertexKey` (key of a vertex).
2432
- * @param {VertexKey} [destVertexKey] - The `destVertexKey` parameter is an optional parameter that
2433
- * represents the key of the destination vertex of the edge. It is used to specify the destination
2434
- * vertex when the `edge` parameter is a vertex key. If `destVertexKey` is not provided, the function
2435
- * assumes that the `edge`
2436
- * @returns the removed edge (EO) or undefined if no edge was removed.
2437
- */
2438
- deleteEdge(edgeOrSrcVertexKey, destVertexKey) {
2439
- let removed = void 0;
2440
- let src, dest;
2441
- if (this.isVertexKey(edgeOrSrcVertexKey)) {
2442
- if (this.isVertexKey(destVertexKey)) {
2443
- src = this._getVertex(edgeOrSrcVertexKey);
2444
- dest = this._getVertex(destVertexKey);
2445
- } else {
2446
- return;
2447
- }
2448
- } else {
2449
- src = this._getVertex(edgeOrSrcVertexKey.src);
2450
- dest = this._getVertex(edgeOrSrcVertexKey.dest);
2451
- }
2452
- if (src && dest) {
2453
- const srcOutEdges = this._outEdgeMap.get(src);
2454
- if (srcOutEdges && srcOutEdges.length > 0) {
2455
- arrayRemove(srcOutEdges, (edge) => edge.src === src.key && edge.dest === dest?.key);
2456
- }
2457
- const destInEdges = this._inEdgeMap.get(dest);
2458
- if (destInEdges && destInEdges.length > 0) {
2459
- removed = arrayRemove(destInEdges, (edge) => edge.src === src.key && edge.dest === dest.key)[0];
2460
- }
2461
- }
2462
- return removed;
2463
- }
2464
- /**
2465
- * Time Complexity: O(1) - Constant time for Map operations.
2466
- * Space Complexity: O(1) - Constant space, as it creates only a few variables.
2467
- *
2468
- * The `deleteVertex` function removes a vertex from a graph by its ID or by the vertex object itself.
2469
- * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID
2470
- * (`VertexKey`).
2471
- * @returns The method is returning a boolean value.
2472
- */
2473
- deleteVertex(vertexOrKey) {
2474
- let vertexKey;
2475
- let vertex;
2476
- if (this.isVertexKey(vertexOrKey)) {
2477
- vertex = this.getVertex(vertexOrKey);
2478
- vertexKey = vertexOrKey;
2479
- } else {
2480
- vertex = vertexOrKey;
2481
- vertexKey = this._getVertexKey(vertexOrKey);
2482
- }
2483
- if (vertex) {
2484
- const neighbors = this.getNeighbors(vertex);
2485
- for (const neighbor of neighbors) {
2486
- this.deleteEdgeSrcToDest(vertex, neighbor);
2487
- }
2488
- this._outEdgeMap.delete(vertex);
2489
- this._inEdgeMap.delete(vertex);
2490
- }
2491
- return this._vertexMap.delete(vertexKey);
2492
- }
2493
- /**
2494
- * Time Complexity: O(|E|) where |E| is the number of edgeMap
2495
- * Space Complexity: O(1)
2496
- *
2497
- * The function removes edgeMap between two vertexMap and returns the removed edgeMap.
2498
- * @param {VertexKey | VO} v1 - The parameter `v1` can be either a `VertexKey` or a `VO`. A `VertexKey` represents the
2499
- * unique identifier of a vertex in a graph, while `VO` represents the actual vertex object.
2500
- * @param {VertexKey | VO} v2 - The parameter `v2` represents either a `VertexKey` or a `VO` object. It is used to specify
2501
- * the second vertex in the edge that needs to be removed.
2502
- * @returns an array of removed edgeMap (EO[]).
2503
- */
2504
- deleteEdgesBetween(v1, v2) {
2505
- const removed = [];
2506
- if (v1 && v2) {
2507
- const v1ToV2 = this.deleteEdgeSrcToDest(v1, v2);
2508
- const v2ToV1 = this.deleteEdgeSrcToDest(v2, v1);
2509
- if (v1ToV2) removed.push(v1ToV2);
2510
- if (v2ToV1) removed.push(v2ToV1);
2511
- }
2512
- return removed;
2513
- }
2514
- /**
2515
- * Time Complexity: O(1)
2516
- * Space Complexity: O(1)
2517
- *
2518
- * The function `incomingEdgesOf` returns an array of incoming edgeMap for a given vertex or vertex ID.
2519
- * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID
2520
- * (`VertexKey`).
2521
- * @returns The method `incomingEdgesOf` returns an array of edgeMap (`EO[]`).
2522
- */
2523
- incomingEdgesOf(vertexOrKey) {
2524
- const target = this._getVertex(vertexOrKey);
2525
- if (target) {
2526
- return this.inEdgeMap.get(target) || [];
2527
- }
2528
- return [];
2529
- }
2530
- /**
2531
- * Time Complexity: O(1)
2532
- * Space Complexity: O(1)
2533
- *
2534
- * The function `outgoingEdgesOf` returns an array of outgoing edgeMap from a given vertex or vertex ID.
2535
- * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can accept either a vertex object (`VO`) or a vertex ID
2536
- * (`VertexKey`).
2537
- * @returns The method `outgoingEdgesOf` returns an array of edgeMap (`EO[]`).
2538
- */
2539
- outgoingEdgesOf(vertexOrKey) {
2540
- const target = this._getVertex(vertexOrKey);
2541
- if (target) {
2542
- return this._outEdgeMap.get(target) || [];
2543
- }
2544
- return [];
2545
- }
2546
- /**
2547
- * Time Complexity: O(1)
2548
- * Space Complexity: O(1)
2549
- *
2550
- * The function "degreeOf" returns the total degree of a vertex, which is the sum of its out-degree and in-degree.
2551
- * @param {VertexKey | VO} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `VO`.
2552
- * @returns The sum of the out-degree and in-degree of the specified vertex or vertex ID.
2553
- */
2554
- degreeOf(vertexOrKey) {
2555
- return this.outDegreeOf(vertexOrKey) + this.inDegreeOf(vertexOrKey);
2556
- }
2557
- /**
2558
- * Time Complexity: O(1)
2559
- * Space Complexity: O(1)
2560
- *
2561
- * The function "inDegreeOf" returns the number of incoming edgeMap for a given vertex.
2562
- * @param {VertexKey | VO} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `VO`.
2563
- * @returns The number of incoming edgeMap of the specified vertex or vertex ID.
2564
- */
2565
- inDegreeOf(vertexOrKey) {
2566
- return this.incomingEdgesOf(vertexOrKey).length;
2567
- }
2568
- /**
2569
- * Time Complexity: O(1)
2570
- * Space Complexity: O(1)
2571
- *
2572
- * The function `outDegreeOf` returns the number of outgoing edgeMap from a given vertex.
2573
- * @param {VertexKey | VO} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `VO`.
2574
- * @returns The number of outgoing edgeMap from the specified vertex or vertex ID.
2575
- */
2576
- outDegreeOf(vertexOrKey) {
2577
- return this.outgoingEdgesOf(vertexOrKey).length;
2578
- }
2579
- /**
2580
- * Time Complexity: O(1)
2581
- * Space Complexity: O(1)
2582
- *
2583
- * The function "edgesOf" returns an array of both outgoing and incoming edgeMap of a given vertex or vertex ID.
2584
- * @param {VertexKey | VO} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `VO`.
2585
- * @returns The function `edgesOf` returns an array of edgeMap.
2586
- */
2587
- edgesOf(vertexOrKey) {
2588
- return [...this.outgoingEdgesOf(vertexOrKey), ...this.incomingEdgesOf(vertexOrKey)];
2589
- }
2590
- /**
2591
- * Time Complexity: O(1)
2592
- * Space Complexity: O(1)
2593
- *
2594
- * The function "getEdgeSrc" returns the source vertex of an edge, or undefined if the edge does not exist.
2595
- * @param {EO} e - The parameter "e" is of type EO, which represents an edge in a graph.
2596
- * @returns either a vertex object (VO) or undefined.
2597
- */
2598
- getEdgeSrc(e) {
2599
- return this._getVertex(e.src);
2600
- }
2601
- /**
2602
- * Time Complexity: O(1)
2603
- * Space Complexity: O(1)
2604
- *
2605
- * The function "getEdgeDest" returns the destination vertex of an edge.
2606
- * @param {EO} e - The parameter "e" is of type "EO", which represents an edge in a graph.
2607
- * @returns either a vertex object of type VO or undefined.
2608
- */
2609
- getEdgeDest(e) {
2610
- return this._getVertex(e.dest);
2611
- }
2612
- /**
2613
- * Time Complexity: O(|E|) where |E| is the number of edgeMap
2614
- * Space Complexity: O(1)
2615
- *
2616
- * The function `getDestinations` returns an array of destination vertexMap connected to a given vertex.
2617
- * @param {VO | VertexKey | undefined} vertex - The `vertex` parameter represents the starting vertex from which we want to
2618
- * find the destinations. It can be either a `VO` object, a `VertexKey` value, or `undefined`.
2619
- * @returns an array of vertexMap (VO[]).
2620
- */
2621
- getDestinations(vertex) {
2622
- if (vertex === void 0) {
2623
- return [];
2624
- }
2625
- const destinations = [];
2626
- const outgoingEdges = this.outgoingEdgesOf(vertex);
2627
- for (const outEdge of outgoingEdges) {
2628
- const child = this.getEdgeDest(outEdge);
2629
- if (child) {
2630
- destinations.push(child);
2631
- }
2632
- }
2633
- return destinations;
2634
- }
2635
- /**
2636
- * Time Complexity: O(|V| + |E|) where |V| is the number of vertexMap and |E| is the number of edgeMap
2637
- * Space Complexity: O(|V|)
2638
- *
2639
- * The `topologicalSort` function performs a topological sort on a graph and returns an array of vertexMap or vertex IDs
2640
- * in the sorted order, or undefined if the graph contains a cycle.
2641
- * @param {'vertex' | 'key'} [propertyName] - The `propertyName` parameter is an optional parameter that specifies the
2642
- * property to use for sorting the vertexMap. It can have two possible values: 'vertex' or 'key'. If 'vertex' is
2643
- * specified, the vertexMap themselves will be used for sorting. If 'key' is specified, the ids of
2644
- * @returns an array of vertexMap or vertex IDs in topological order. If there is a cycle in the graph, it returns undefined.
2645
- */
2646
- topologicalSort(propertyName) {
2647
- propertyName = propertyName ?? "key";
2648
- const statusMap = /* @__PURE__ */ new Map();
2649
- for (const entry of this.vertexMap) {
2650
- statusMap.set(entry[1], 0);
2651
- }
2652
- let sorted = [];
2653
- let hasCycle = false;
2654
- const dfs = (cur) => {
2655
- statusMap.set(cur, 1);
2656
- const children = this.getDestinations(cur);
2657
- for (const child of children) {
2658
- const childStatus = statusMap.get(child);
2659
- if (childStatus === 0) {
2660
- dfs(child);
2661
- } else if (childStatus === 1) {
2662
- hasCycle = true;
2663
- }
2664
- }
2665
- statusMap.set(cur, 2);
2666
- sorted.push(cur);
2667
- };
2668
- for (const entry of this.vertexMap) {
2669
- if (statusMap.get(entry[1]) === 0) {
2670
- dfs(entry[1]);
2671
- }
2672
- }
2673
- if (hasCycle) return void 0;
2674
- if (propertyName === "key") sorted = sorted.map((vertex) => vertex instanceof DirectedVertex ? vertex.key : vertex);
2675
- return sorted.reverse();
2676
- }
2677
- /**
2678
- * Time Complexity: O(|E|) where |E| is the number of edgeMap
2679
- * Space Complexity: O(|E|)
2680
- *
2681
- * The `edgeSet` function returns an array of all the edgeMap in the graph.
2682
- * @returns The `edgeSet()` method returns an array of edgeMap (`EO[]`).
2683
- */
2684
- edgeSet() {
2685
- let edgeMap = [];
2686
- this._outEdgeMap.forEach((outEdges) => {
2687
- edgeMap = [...edgeMap, ...outEdges];
2688
- });
2689
- return edgeMap;
2690
- }
2691
- /**
2692
- * Time Complexity: O(|E|) where |E| is the number of edgeMap
2693
- * Space Complexity: O(1)
2694
- *
2695
- * The function `getNeighbors` returns an array of neighboring vertexMap of a given vertex or vertex ID in a graph.
2696
- * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID
2697
- * (`VertexKey`).
2698
- * @returns an array of vertexMap (VO[]).
2699
- */
2700
- getNeighbors(vertexOrKey) {
2701
- const neighbors = [];
2702
- const vertex = this._getVertex(vertexOrKey);
2703
- if (vertex) {
2704
- const outEdges = this.outgoingEdgesOf(vertex);
2705
- for (const outEdge of outEdges) {
2706
- const neighbor = this._getVertex(outEdge.dest);
2707
- if (neighbor) {
2708
- neighbors.push(neighbor);
2709
- }
2710
- }
2711
- }
2712
- return neighbors;
2713
- }
2714
- /**
2715
- * Time Complexity: O(1)
2716
- * Space Complexity: O(1)
2717
- *
2718
- * The function "getEndsOfEdge" returns the source and destination vertexMap of an edge if it exists in the graph,
2719
- * otherwise it returns undefined.
2720
- * @param {EO} edge - The parameter `edge` is of type `EO`, which represents an edge in a graph.
2721
- * @returns The function `getEndsOfEdge` returns an array containing two vertexMap `[VO, VO]` if the edge exists in the
2722
- * graph. If the edge does not exist, it returns `undefined`.
2723
- */
2724
- getEndsOfEdge(edge) {
2725
- if (!this.hasEdge(edge.src, edge.dest)) {
2726
- return void 0;
2727
- }
2728
- const v1 = this._getVertex(edge.src);
2729
- const v2 = this._getVertex(edge.dest);
2730
- if (v1 && v2) {
2731
- return [v1, v2];
2732
- } else {
2733
- return void 0;
2734
- }
2735
- }
2736
- /**
2737
- * The isEmpty function checks if the graph is empty.
2738
- *
2739
- * @return A boolean value
2740
- */
2741
- isEmpty() {
2742
- return this.vertexMap.size === 0 && this.inEdgeMap.size === 0 && this.outEdgeMap.size === 0;
2743
- }
2744
- /**
2745
- * Time Complexity: O(1)
2746
- * Space Complexity: O(1)
2747
- *
2748
- * The clear function resets the vertex map, in-edge map, and out-edge map.
2749
- */
2750
- clear() {
2751
- this._vertexMap = /* @__PURE__ */ new Map();
2752
- this._inEdgeMap = /* @__PURE__ */ new Map();
2753
- this._outEdgeMap = /* @__PURE__ */ new Map();
2754
- }
2755
- /**
2756
- * The clone function creates a new DirectedGraph object with the same vertices and edges as the original.
2757
- *
2758
- * @return A new instance of the directedgraph class
2759
- */
2760
- clone() {
2761
- const cloned = new _DirectedGraph();
2762
- cloned.vertexMap = new Map(this.vertexMap);
2763
- cloned.inEdgeMap = new Map(this.inEdgeMap);
2764
- cloned.outEdgeMap = new Map(this.outEdgeMap);
2765
- return cloned;
2766
- }
2767
- /**
2768
- * Time Complexity: O(V + E)
2769
- * Space Complexity: O(V)
2770
- * Tarjan is an algorithm based on dfs,which is used to solve the connectivity problem of graphs.
2771
- * Tarjan can find the SSC(strongly connected components), articulation points, and bridges of directed graphs.
2772
- *
2773
- * The function `tarjan` implements the Tarjan's algorithm to find strongly connected components in a
2774
- * graph.
2775
- * @returns The function `tarjan()` returns an object with three properties: `dfnMap`, `lowMap`, and
2776
- * `SCCs`.
2777
- */
2778
- tarjan() {
2779
- const dfnMap = /* @__PURE__ */ new Map();
2780
- const lowMap = /* @__PURE__ */ new Map();
2781
- const SCCs = /* @__PURE__ */ new Map();
2782
- let time = 0;
2783
- const stack = [];
2784
- const inStack = /* @__PURE__ */ new Set();
2785
- const dfs = (vertex) => {
2786
- dfnMap.set(vertex, time);
2787
- lowMap.set(vertex, time);
2788
- time++;
2789
- stack.push(vertex);
2790
- inStack.add(vertex);
2791
- const neighbors = this.getNeighbors(vertex);
2792
- for (const neighbor of neighbors) {
2793
- if (!dfnMap.has(neighbor)) {
2794
- dfs(neighbor);
2795
- lowMap.set(vertex, Math.min(lowMap.get(vertex), lowMap.get(neighbor)));
2796
- } else if (inStack.has(neighbor)) {
2797
- lowMap.set(vertex, Math.min(lowMap.get(vertex), dfnMap.get(neighbor)));
2798
- }
2799
- }
2800
- if (dfnMap.get(vertex) === lowMap.get(vertex)) {
2801
- const SCC = [];
2802
- let poppedVertex;
2803
- do {
2804
- poppedVertex = stack.pop();
2805
- inStack.delete(poppedVertex);
2806
- SCC.push(poppedVertex);
2807
- } while (poppedVertex !== vertex);
2808
- SCCs.set(SCCs.size, SCC);
2809
- }
2810
- };
2811
- for (const vertex of this.vertexMap.values()) {
2812
- if (!dfnMap.has(vertex)) {
2813
- dfs(vertex);
2814
- }
2815
- }
2816
- return { dfnMap, lowMap, SCCs };
2817
- }
2818
- /**
2819
- * Time Complexity: O(V + E) - Depends on the implementation (Tarjan's algorithm).
2820
- * Space Complexity: O(V) - Depends on the implementation (Tarjan's algorithm).
2821
- *
2822
- * The function returns a map that associates each vertex object with its corresponding depth-first
2823
- * number.
2824
- * @returns A Map object with keys of type VO and values of type number.
2825
- */
2826
- getDFNMap() {
2827
- return this.tarjan().dfnMap;
2828
- }
2829
- /**
2830
- * The function returns a Map object that contains the low values of each vertex in a Tarjan
2831
- * algorithm.
2832
- * @returns The method `getLowMap()` is returning a `Map` object with keys of type `VO` and values of
2833
- * type `number`.
2834
- */
2835
- getLowMap() {
2836
- return this.tarjan().lowMap;
2837
- }
2838
- /**
2839
- * The function "getSCCs" returns a map of strongly connected components (SCCs) using the Tarjan
2840
- * algorithm.
2841
- * @returns a map where the keys are numbers and the values are arrays of VO objects.
2842
- */
2843
- getSCCs() {
2844
- return this.tarjan().SCCs;
2845
- }
2846
- /**
2847
- * Time Complexity: O(1)
2848
- * Space Complexity: O(1)
2849
- *
2850
- * The function `_addEdge` adds an edge to a graph if the source and destination vertexMap exist.
2851
- * @param {EO} edge - The parameter `edge` is of type `EO`, which represents an edge in a graph. It is the edge that
2852
- * needs to be added to the graph.
2853
- * @returns a boolean value. It returns true if the edge was successfully added to the graph, and false if either the
2854
- * source or destination vertex does not exist in the graph.
2855
- */
2856
- _addEdge(edge) {
2857
- if (!(this.hasVertex(edge.src) && this.hasVertex(edge.dest))) {
2858
- return false;
2859
- }
2860
- const srcVertex = this._getVertex(edge.src);
2861
- const destVertex = this._getVertex(edge.dest);
2862
- if (srcVertex && destVertex) {
2863
- const srcOutEdges = this._outEdgeMap.get(srcVertex);
2864
- if (srcOutEdges) {
2865
- srcOutEdges.push(edge);
2866
- } else {
2867
- this._outEdgeMap.set(srcVertex, [edge]);
2868
- }
2869
- const destInEdges = this._inEdgeMap.get(destVertex);
2870
- if (destInEdges) {
2871
- destInEdges.push(edge);
2872
- } else {
2873
- this._inEdgeMap.set(destVertex, [edge]);
2874
- }
2875
- return true;
2876
- } else {
2877
- return false;
2878
- }
2879
- }
2880
- };
2881
- export {
2882
- DirectedEdge,
2883
- DirectedGraph,
2884
- DirectedVertex
2885
- };
2886
- /**
2887
- * data-structure-typed
2888
- *
2889
- * @author Pablo Zeng
2890
- * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
2891
- * @license MIT License
2892
- */
2893
- /**
2894
- * data-structure-typed
2895
- * @author Kirk Qi
2896
- * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>
2897
- * @license MIT License
2898
- */
2899
- /**
2900
- * data-structure-typed
2901
- *
2902
- * @author Kirk Qi
2903
- * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>
2904
- * @license MIT License
2905
- */
2906
- /**
2907
- * @license MIT
2908
- * @copyright Pablo Zeng <zrwusa@gmail.com>
2909
- * @class
2910
- */