doubly-linked-list-typed 1.53.1 → 1.53.3

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.
@@ -68,6 +68,432 @@ exports.DoublyLinkedListNode = DoublyLinkedListNode;
68
68
  * 2. Bidirectional Traversal: Unlike singly linked lists, doubly linked lists can be easily traversed forwards or backwards. This makes insertions and deletions in the list more flexible and efficient.
69
69
  * 3. No Centralized Index: Unlike arrays, elements in a linked list are not stored contiguously, so there is no centralized index. Accessing elements in a linked list typically requires traversing from the head or tail node.
70
70
  * 4. High Efficiency in Insertion and Deletion: Adding or removing elements in a linked list does not require moving other elements, making these operations more efficient than in arrays.
71
+ * @example
72
+ * // text editor operation history
73
+ * const actions = [
74
+ * { type: 'insert', content: 'first line of text' },
75
+ * { type: 'insert', content: 'second line of text' },
76
+ * { type: 'delete', content: 'delete the first line' }
77
+ * ];
78
+ * const editorHistory = new DoublyLinkedList<{ type: string; content: string }>(actions);
79
+ *
80
+ * console.log(editorHistory.last?.type); // 'delete'
81
+ * console.log(editorHistory.pop()?.content); // 'delete the first line'
82
+ * console.log(editorHistory.last?.type); // 'insert'
83
+ * @example
84
+ * // Browser history
85
+ * const browserHistory = new DoublyLinkedList<string>();
86
+ *
87
+ * browserHistory.push('home page');
88
+ * browserHistory.push('search page');
89
+ * browserHistory.push('details page');
90
+ *
91
+ * console.log(browserHistory.last); // 'details page'
92
+ * console.log(browserHistory.pop()); // 'details page'
93
+ * console.log(browserHistory.last); // 'search page'
94
+ * @example
95
+ * // Use DoublyLinkedList to implement music player
96
+ * // Define the Song interface
97
+ * interface Song {
98
+ * title: string;
99
+ * artist: string;
100
+ * duration: number; // duration in seconds
101
+ * }
102
+ *
103
+ * class Player {
104
+ * private playlist: DoublyLinkedList<Song>;
105
+ * private currentSong: ReturnType<typeof this.playlist.getNodeAt> | undefined;
106
+ *
107
+ * constructor(songs: Song[]) {
108
+ * this.playlist = new DoublyLinkedList<Song>();
109
+ * songs.forEach(song => this.playlist.push(song));
110
+ * this.currentSong = this.playlist.head;
111
+ * }
112
+ *
113
+ * // Play the next song in the playlist
114
+ * playNext(): Song | undefined {
115
+ * if (!this.currentSong?.next) {
116
+ * this.currentSong = this.playlist.head; // Loop to the first song
117
+ * } else {
118
+ * this.currentSong = this.currentSong.next;
119
+ * }
120
+ * return this.currentSong?.value;
121
+ * }
122
+ *
123
+ * // Play the previous song in the playlist
124
+ * playPrevious(): Song | undefined {
125
+ * if (!this.currentSong?.prev) {
126
+ * this.currentSong = this.playlist.tail; // Loop to the last song
127
+ * } else {
128
+ * this.currentSong = this.currentSong.prev;
129
+ * }
130
+ * return this.currentSong?.value;
131
+ * }
132
+ *
133
+ * // Get the current song
134
+ * getCurrentSong(): Song | undefined {
135
+ * return this.currentSong?.value;
136
+ * }
137
+ *
138
+ * // Loop through the playlist twice
139
+ * loopThroughPlaylist(): Song[] {
140
+ * const playedSongs: Song[] = [];
141
+ * const initialNode = this.currentSong;
142
+ *
143
+ * // Loop through the playlist twice
144
+ * for (let i = 0; i < this.playlist.size * 2; i++) {
145
+ * playedSongs.push(this.currentSong!.value);
146
+ * this.currentSong = this.currentSong!.next || this.playlist.head; // Loop back to the start if needed
147
+ * }
148
+ *
149
+ * // Reset the current song to the initial song
150
+ * this.currentSong = initialNode;
151
+ * return playedSongs;
152
+ * }
153
+ * }
154
+ *
155
+ * const songs = [
156
+ * { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
157
+ * { title: 'Hotel California', artist: 'Eagles', duration: 391 },
158
+ * { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
159
+ * { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
160
+ * ];
161
+ * let player = new Player(songs);
162
+ * // should play the next song
163
+ * player = new Player(songs);
164
+ * const firstSong = player.getCurrentSong();
165
+ * const nextSong = player.playNext();
166
+ *
167
+ * // Expect the next song to be "Hotel California by Eagles"
168
+ * console.log(nextSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }
169
+ * console.log(firstSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
170
+ *
171
+ * // should play the previous song
172
+ * player = new Player(songs);
173
+ * player.playNext(); // Move to the second song
174
+ * const currentSong = player.getCurrentSong();
175
+ * const previousSong = player.playPrevious();
176
+ *
177
+ * // Expect the previous song to be "Bohemian Rhapsody by Queen"
178
+ * console.log(previousSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
179
+ * console.log(currentSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }
180
+ *
181
+ * // should loop to the first song when playing next from the last song
182
+ * player = new Player(songs);
183
+ * player.playNext(); // Move to the second song
184
+ * player.playNext(); // Move to the third song
185
+ * player.playNext(); // Move to the fourth song
186
+ *
187
+ * const nextSongToFirst = player.playNext(); // Should loop to the first song
188
+ *
189
+ * // Expect the next song to be "Bohemian Rhapsody by Queen"
190
+ * console.log(nextSongToFirst); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
191
+ *
192
+ * // should loop to the last song when playing previous from the first song
193
+ * player = new Player(songs);
194
+ * player.playNext(); // Move to the first song
195
+ * player.playNext(); // Move to the second song
196
+ * player.playNext(); // Move to the third song
197
+ * player.playNext(); // Move to the fourth song
198
+ *
199
+ * const previousToLast = player.playPrevious(); // Should loop to the last song
200
+ *
201
+ * // Expect the previous song to be "Billie Jean by Michael Jackson"
202
+ * console.log(previousToLast); // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
203
+ *
204
+ * // should loop through the entire playlist
205
+ * player = new Player(songs);
206
+ * const playedSongs = player.loopThroughPlaylist();
207
+ *
208
+ * // The expected order of songs for two loops
209
+ * console.log(playedSongs); // [
210
+ * // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
211
+ * // { title: 'Hotel California', artist: 'Eagles', duration: 391 },
212
+ * // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
213
+ * // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 },
214
+ * // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
215
+ * // { title: 'Hotel California', artist: 'Eagles', duration: 391 },
216
+ * // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
217
+ * // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
218
+ * // ]
219
+ * @example
220
+ * // Use DoublyLinkedList to implement LRU cache
221
+ * interface CacheEntry<K, V> {
222
+ * key: K;
223
+ * value: V;
224
+ * }
225
+ *
226
+ * class LRUCache<K = string, V = any> {
227
+ * private readonly capacity: number;
228
+ * private list: DoublyLinkedList<CacheEntry<K, V>>;
229
+ * private map: Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>;
230
+ *
231
+ * constructor(capacity: number) {
232
+ * if (capacity <= 0) {
233
+ * throw new Error('lru cache capacity must be greater than 0');
234
+ * }
235
+ * this.capacity = capacity;
236
+ * this.list = new DoublyLinkedList<CacheEntry<K, V>>();
237
+ * this.map = new Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>();
238
+ * }
239
+ *
240
+ * // Get cached value
241
+ * get(key: K): V | undefined {
242
+ * const node = this.map.get(key);
243
+ *
244
+ * if (!node) return undefined;
245
+ *
246
+ * // Move the visited node to the head of the linked list (most recently used)
247
+ * this.moveToFront(node);
248
+ *
249
+ * return node.value.value;
250
+ * }
251
+ *
252
+ * // Set cache value
253
+ * set(key: K, value: V): void {
254
+ * // Check if it already exists
255
+ * const node = this.map.get(key);
256
+ *
257
+ * if (node) {
258
+ * // Update value and move to head
259
+ * node.value.value = value;
260
+ * this.moveToFront(node);
261
+ * return;
262
+ * }
263
+ *
264
+ * // Check capacity
265
+ * if (this.list.size >= this.capacity) {
266
+ * // Delete the least recently used element (the tail of the linked list)
267
+ * const removedNode = this.list.tail;
268
+ * if (removedNode) {
269
+ * this.map.delete(removedNode.value.key);
270
+ * this.list.pop();
271
+ * }
272
+ * }
273
+ *
274
+ * // Create new node and add to head
275
+ * const newEntry: CacheEntry<K, V> = { key, value };
276
+ * this.list.unshift(newEntry);
277
+ *
278
+ * // Save node reference in map
279
+ * const newNode = this.list.head;
280
+ * if (newNode) {
281
+ * this.map.set(key, newNode);
282
+ * }
283
+ * }
284
+ *
285
+ * // Move the node to the head of the linked list
286
+ * private moveToFront(node: DoublyLinkedListNode<CacheEntry<K, V>>): void {
287
+ * this.list.delete(node);
288
+ * this.list.unshift(node.value);
289
+ * }
290
+ *
291
+ * // Delete specific key
292
+ * delete(key: K): boolean {
293
+ * const node = this.map.get(key);
294
+ * if (!node) return false;
295
+ *
296
+ * // Remove from linked list
297
+ * this.list.delete(node);
298
+ * // Remove from map
299
+ * this.map.delete(key);
300
+ *
301
+ * return true;
302
+ * }
303
+ *
304
+ * // Clear cache
305
+ * clear(): void {
306
+ * this.list.clear();
307
+ * this.map.clear();
308
+ * }
309
+ *
310
+ * // Get the current cache size
311
+ * get size(): number {
312
+ * return this.list.size;
313
+ * }
314
+ *
315
+ * // Check if it is empty
316
+ * get isEmpty(): boolean {
317
+ * return this.list.isEmpty();
318
+ * }
319
+ * }
320
+ *
321
+ * // should set and get values correctly
322
+ * const cache = new LRUCache<string, number>(3);
323
+ * cache.set('a', 1);
324
+ * cache.set('b', 2);
325
+ * cache.set('c', 3);
326
+ *
327
+ * console.log(cache.get('a')); // 1
328
+ * console.log(cache.get('b')); // 2
329
+ * console.log(cache.get('c')); // 3
330
+ *
331
+ * // The least recently used element should be evicted when capacity is exceeded
332
+ * cache.clear();
333
+ * cache.set('a', 1);
334
+ * cache.set('b', 2);
335
+ * cache.set('c', 3);
336
+ * cache.set('d', 4); // This will eliminate 'a'
337
+ *
338
+ * console.log(cache.get('a')).toBeUndefined();
339
+ * expect(cache.get('b')); // 2
340
+ * console.log(cache.get('c')); // 3
341
+ * console.log(cache.get('d')); // 4
342
+ *
343
+ * // The priority of an element should be updated when it is accessed
344
+ * cache.clear();
345
+ * cache.set('a', 1);
346
+ * cache.set('b', 2);
347
+ * cache.set('c', 3);
348
+ *
349
+ * cache.get('a'); // access 'a'
350
+ * cache.set('d', 4); // This will eliminate 'b'
351
+ *
352
+ * console.log(cache.get('a')); // 1
353
+ * console.log(cache.get('b')).toBeUndefined();
354
+ * expect(cache.get('c')); // 3
355
+ * console.log(cache.get('d')); // 4
356
+ *
357
+ * // Should support updating existing keys
358
+ * cache.clear();
359
+ * cache.set('a', 1);
360
+ * cache.set('a', 10);
361
+ *
362
+ * console.log(cache.get('a')); // 10
363
+ *
364
+ * // Should support deleting specified keys
365
+ * cache.clear();
366
+ * cache.set('a', 1);
367
+ * cache.set('b', 2);
368
+ *
369
+ * console.log(cache.delete('a')); // true
370
+ * console.log(cache.get('a')).toBeUndefined();
371
+ * expect(cache.size); // 1
372
+ *
373
+ * // Should support clearing cache
374
+ * cache.clear();
375
+ * cache.set('a', 1);
376
+ * cache.set('b', 2);
377
+ * cache.clear();
378
+ *
379
+ * console.log(cache.size); // 0
380
+ * console.log(cache.isEmpty); // true
381
+ * @example
382
+ * // finding lyrics by timestamp in Coldplay's "Fix You"
383
+ * // Create a DoublyLinkedList to store song lyrics with timestamps
384
+ * const lyricsList = new DoublyLinkedList<{ time: number; text: string }>();
385
+ *
386
+ * // Detailed lyrics with precise timestamps (in milliseconds)
387
+ * const lyrics = [
388
+ * { time: 0, text: "When you try your best, but you don't succeed" },
389
+ * { time: 4000, text: 'When you get what you want, but not what you need' },
390
+ * { time: 8000, text: "When you feel so tired, but you can't sleep" },
391
+ * { time: 12000, text: 'Stuck in reverse' },
392
+ * { time: 16000, text: 'And the tears come streaming down your face' },
393
+ * { time: 20000, text: "When you lose something you can't replace" },
394
+ * { time: 24000, text: 'When you love someone, but it goes to waste' },
395
+ * { time: 28000, text: 'Could it be worse?' },
396
+ * { time: 32000, text: 'Lights will guide you home' },
397
+ * { time: 36000, text: 'And ignite your bones' },
398
+ * { time: 40000, text: 'And I will try to fix you' }
399
+ * ];
400
+ *
401
+ * // Populate the DoublyLinkedList with lyrics
402
+ * lyrics.forEach(lyric => lyricsList.push(lyric));
403
+ *
404
+ * // Test different scenarios of lyric synchronization
405
+ *
406
+ * // 1. Find lyric at exact timestamp
407
+ * const exactTimeLyric = lyricsList.findBackward(lyric => lyric.time <= 36000);
408
+ * console.log(exactTimeLyric?.text); // 'And ignite your bones'
409
+ *
410
+ * // 2. Find lyric between timestamps
411
+ * const betweenTimeLyric = lyricsList.findBackward(lyric => lyric.time <= 22000);
412
+ * console.log(betweenTimeLyric?.text); // "When you lose something you can't replace"
413
+ *
414
+ * // 3. Find first lyric when timestamp is less than first entry
415
+ * const earlyTimeLyric = lyricsList.findBackward(lyric => lyric.time <= -1000);
416
+ * console.log(earlyTimeLyric).toBeUndefined();
417
+ *
418
+ * // 4. Find last lyric when timestamp is after last entry
419
+ * const lateTimeLyric = lyricsList.findBackward(lyric => lyric.time <= 50000);
420
+ * expect(lateTimeLyric?.text); // 'And I will try to fix you'
421
+ * @example
422
+ * // cpu process schedules
423
+ * class Process {
424
+ * constructor(
425
+ * public id: number,
426
+ * public priority: number
427
+ * ) {}
428
+ *
429
+ * execute(): string {
430
+ * return `Process ${this.id} executed.`;
431
+ * }
432
+ * }
433
+ *
434
+ * class Scheduler {
435
+ * private queue: DoublyLinkedList<Process>;
436
+ *
437
+ * constructor() {
438
+ * this.queue = new DoublyLinkedList<Process>();
439
+ * }
440
+ *
441
+ * addProcess(process: Process): void {
442
+ * // Insert processes into a queue based on priority, keeping priority in descending order
443
+ * let current = this.queue.head;
444
+ * while (current && current.value.priority >= process.priority) {
445
+ * current = current.next;
446
+ * }
447
+ *
448
+ * if (!current) {
449
+ * this.queue.push(process);
450
+ * } else {
451
+ * this.queue.addBefore(current, process);
452
+ * }
453
+ * }
454
+ *
455
+ * executeNext(): string | undefined {
456
+ * // Execute tasks at the head of the queue in order
457
+ * const process = this.queue.shift();
458
+ * return process ? process.execute() : undefined;
459
+ * }
460
+ *
461
+ * listProcesses(): string[] {
462
+ * return this.queue.toArray().map(process => `Process ${process.id} (Priority: ${process.priority})`);
463
+ * }
464
+ *
465
+ * clear(): void {
466
+ * this.queue.clear();
467
+ * }
468
+ * }
469
+ *
470
+ * // should add processes based on priority
471
+ * let scheduler = new Scheduler();
472
+ * scheduler.addProcess(new Process(1, 10));
473
+ * scheduler.addProcess(new Process(2, 20));
474
+ * scheduler.addProcess(new Process(3, 15));
475
+ *
476
+ * console.log(scheduler.listProcesses()); // [
477
+ * // 'Process 2 (Priority: 20)',
478
+ * // 'Process 3 (Priority: 15)',
479
+ * // 'Process 1 (Priority: 10)'
480
+ * // ]
481
+ *
482
+ * // should execute the highest priority process
483
+ * scheduler = new Scheduler();
484
+ * scheduler.addProcess(new Process(1, 10));
485
+ * scheduler.addProcess(new Process(2, 20));
486
+ *
487
+ * console.log(scheduler.executeNext()); // 'Process 2 executed.'
488
+ * console.log(scheduler.listProcesses()); // ['Process 1 (Priority: 10)']
489
+ *
490
+ * // should clear all processes
491
+ * scheduler = new Scheduler();
492
+ * scheduler.addProcess(new Process(1, 10));
493
+ * scheduler.addProcess(new Process(2, 20));
494
+ *
495
+ * scheduler.clear();
496
+ * console.log(scheduler.listProcesses()); // []
71
497
  */
72
498
  class DoublyLinkedList extends base_1.IterableElementBase {
73
499
  constructor(elements = [], options) {
@@ -453,8 +879,10 @@ class DoublyLinkedList extends base_1.IterableElementBase {
453
879
  else {
454
880
  const prevNode = node.prev;
455
881
  const nextNode = node.next;
456
- prevNode.next = nextNode;
457
- nextNode.prev = prevNode;
882
+ if (prevNode)
883
+ prevNode.next = nextNode;
884
+ if (nextNode)
885
+ nextNode.prev = prevNode;
458
886
  this._size--;
459
887
  }
460
888
  return true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doubly-linked-list-typed",
3
- "version": "1.53.1",
3
+ "version": "1.53.3",
4
4
  "description": "Doubly Linked List. Javascript & Typescript Data Structure.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -64,6 +64,6 @@
64
64
  "typescript": "^4.9.5"
65
65
  },
66
66
  "dependencies": {
67
- "data-structure-typed": "^1.53.1"
67
+ "data-structure-typed": "^1.53.3"
68
68
  }
69
69
  }
@@ -19,6 +19,171 @@ import { IterableElementBase } from '../base';
19
19
  * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.
20
20
  * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.
21
21
  * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prime's minimum-spanning tree algorithm, which use heaps to improve performance.
22
+ * @example
23
+ * // Use Heap to sort an array
24
+ * function heapSort(arr: number[]): number[] {
25
+ * const heap = new Heap<number>(arr, { comparator: (a, b) => a - b });
26
+ * const sorted: number[] = [];
27
+ * while (!heap.isEmpty()) {
28
+ * sorted.push(heap.poll()!); // Poll minimum element
29
+ * }
30
+ * return sorted;
31
+ * }
32
+ *
33
+ * const array = [5, 3, 8, 4, 1, 2];
34
+ * console.log(heapSort(array)); // [1, 2, 3, 4, 5, 8]
35
+ * @example
36
+ * // Use Heap to solve top k problems
37
+ * function topKElements(arr: number[], k: number): number[] {
38
+ * const heap = new Heap<number>([], { comparator: (a, b) => b - a }); // Max heap
39
+ * arr.forEach(num => {
40
+ * heap.add(num);
41
+ * if (heap.size > k) heap.poll(); // Keep the heap size at K
42
+ * });
43
+ * return heap.toArray();
44
+ * }
45
+ *
46
+ * const numbers = [10, 30, 20, 5, 15, 25];
47
+ * console.log(topKElements(numbers, 3)); // [15, 10, 5]
48
+ * @example
49
+ * // Use Heap to merge sorted sequences
50
+ * function mergeSortedSequences(sequences: number[][]): number[] {
51
+ * const heap = new Heap<{ value: number; seqIndex: number; itemIndex: number }>([], {
52
+ * comparator: (a, b) => a.value - b.value // Min heap
53
+ * });
54
+ *
55
+ * // Initialize heap
56
+ * sequences.forEach((seq, seqIndex) => {
57
+ * if (seq.length) {
58
+ * heap.add({ value: seq[0], seqIndex, itemIndex: 0 });
59
+ * }
60
+ * });
61
+ *
62
+ * const merged: number[] = [];
63
+ * while (!heap.isEmpty()) {
64
+ * const { value, seqIndex, itemIndex } = heap.poll()!;
65
+ * merged.push(value);
66
+ *
67
+ * if (itemIndex + 1 < sequences[seqIndex].length) {
68
+ * heap.add({
69
+ * value: sequences[seqIndex][itemIndex + 1],
70
+ * seqIndex,
71
+ * itemIndex: itemIndex + 1
72
+ * });
73
+ * }
74
+ * }
75
+ *
76
+ * return merged;
77
+ * }
78
+ *
79
+ * const sequences = [
80
+ * [1, 4, 7],
81
+ * [2, 5, 8],
82
+ * [3, 6, 9]
83
+ * ];
84
+ * console.log(mergeSortedSequences(sequences)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
85
+ * @example
86
+ * // Use Heap to dynamically maintain the median
87
+ * class MedianFinder {
88
+ * private low: MaxHeap<number>; // Max heap, stores the smaller half
89
+ * private high: MinHeap<number>; // Min heap, stores the larger half
90
+ *
91
+ * constructor() {
92
+ * this.low = new MaxHeap<number>([]);
93
+ * this.high = new MinHeap<number>([]);
94
+ * }
95
+ *
96
+ * addNum(num: number): void {
97
+ * if (this.low.isEmpty() || num <= this.low.peek()!) this.low.add(num);
98
+ * else this.high.add(num);
99
+ *
100
+ * // Balance heaps
101
+ * if (this.low.size > this.high.size + 1) this.high.add(this.low.poll()!);
102
+ * else if (this.high.size > this.low.size) this.low.add(this.high.poll()!);
103
+ * }
104
+ *
105
+ * findMedian(): number {
106
+ * if (this.low.size === this.high.size) return (this.low.peek()! + this.high.peek()!) / 2;
107
+ * return this.low.peek()!;
108
+ * }
109
+ * }
110
+ *
111
+ * const medianFinder = new MedianFinder();
112
+ * medianFinder.addNum(10);
113
+ * console.log(medianFinder.findMedian()); // 10
114
+ * medianFinder.addNum(20);
115
+ * console.log(medianFinder.findMedian()); // 15
116
+ * medianFinder.addNum(30);
117
+ * console.log(medianFinder.findMedian()); // 20
118
+ * medianFinder.addNum(40);
119
+ * console.log(medianFinder.findMedian()); // 25
120
+ * medianFinder.addNum(50);
121
+ * console.log(medianFinder.findMedian()); // 30
122
+ * @example
123
+ * // Use Heap for load balancing
124
+ * function loadBalance(requests: number[], servers: number): number[] {
125
+ * const serverHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // min heap
126
+ * const serverLoads = new Array(servers).fill(0);
127
+ *
128
+ * for (let i = 0; i < servers; i++) {
129
+ * serverHeap.add({ id: i, load: 0 });
130
+ * }
131
+ *
132
+ * requests.forEach(req => {
133
+ * const server = serverHeap.poll()!;
134
+ * serverLoads[server.id] += req;
135
+ * server.load += req;
136
+ * serverHeap.add(server); // The server after updating the load is re-entered into the heap
137
+ * });
138
+ *
139
+ * return serverLoads;
140
+ * }
141
+ *
142
+ * const requests = [5, 2, 8, 3, 7];
143
+ * console.log(loadBalance(requests, 3)); // [12, 8, 5]
144
+ * @example
145
+ * // Use Heap to schedule tasks
146
+ * type Task = [string, number];
147
+ *
148
+ * function scheduleTasks(tasks: Task[], machines: number): Map<number, Task[]> {
149
+ * const machineHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // Min heap
150
+ * const allocation = new Map<number, Task[]>();
151
+ *
152
+ * // Initialize the load on each machine
153
+ * for (let i = 0; i < machines; i++) {
154
+ * machineHeap.add({ id: i, load: 0 });
155
+ * allocation.set(i, []);
156
+ * }
157
+ *
158
+ * // Assign tasks
159
+ * tasks.forEach(([task, load]) => {
160
+ * const machine = machineHeap.poll()!;
161
+ * allocation.get(machine.id)!.push([task, load]);
162
+ * machine.load += load;
163
+ * machineHeap.add(machine); // The machine after updating the load is re-entered into the heap
164
+ * });
165
+ *
166
+ * return allocation;
167
+ * }
168
+ *
169
+ * const tasks: Task[] = [
170
+ * ['Task1', 3],
171
+ * ['Task2', 1],
172
+ * ['Task3', 2],
173
+ * ['Task4', 5],
174
+ * ['Task5', 4]
175
+ * ];
176
+ * const expectedMap = new Map<number, Task[]>();
177
+ * expectedMap.set(0, [
178
+ * ['Task1', 3],
179
+ * ['Task4', 5]
180
+ * ]);
181
+ * expectedMap.set(1, [
182
+ * ['Task2', 1],
183
+ * ['Task3', 2],
184
+ * ['Task5', 4]
185
+ * ]);
186
+ * console.log(scheduleTasks(tasks, 2)); // expectedMap
22
187
  */
23
188
  export class Heap<E = any, R = any> extends IterableElementBase<E, R, Heap<E, R>> {
24
189
  /**