directed-graph-typed 1.53.2 → 1.53.4

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.
@@ -86,6 +86,432 @@ export class DoublyLinkedListNode<E = any> {
86
86
  * 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.
87
87
  * 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.
88
88
  * 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.
89
+ * @example
90
+ * // text editor operation history
91
+ * const actions = [
92
+ * { type: 'insert', content: 'first line of text' },
93
+ * { type: 'insert', content: 'second line of text' },
94
+ * { type: 'delete', content: 'delete the first line' }
95
+ * ];
96
+ * const editorHistory = new DoublyLinkedList<{ type: string; content: string }>(actions);
97
+ *
98
+ * console.log(editorHistory.last?.type); // 'delete'
99
+ * console.log(editorHistory.pop()?.content); // 'delete the first line'
100
+ * console.log(editorHistory.last?.type); // 'insert'
101
+ * @example
102
+ * // Browser history
103
+ * const browserHistory = new DoublyLinkedList<string>();
104
+ *
105
+ * browserHistory.push('home page');
106
+ * browserHistory.push('search page');
107
+ * browserHistory.push('details page');
108
+ *
109
+ * console.log(browserHistory.last); // 'details page'
110
+ * console.log(browserHistory.pop()); // 'details page'
111
+ * console.log(browserHistory.last); // 'search page'
112
+ * @example
113
+ * // Use DoublyLinkedList to implement music player
114
+ * // Define the Song interface
115
+ * interface Song {
116
+ * title: string;
117
+ * artist: string;
118
+ * duration: number; // duration in seconds
119
+ * }
120
+ *
121
+ * class Player {
122
+ * private playlist: DoublyLinkedList<Song>;
123
+ * private currentSong: ReturnType<typeof this.playlist.getNodeAt> | undefined;
124
+ *
125
+ * constructor(songs: Song[]) {
126
+ * this.playlist = new DoublyLinkedList<Song>();
127
+ * songs.forEach(song => this.playlist.push(song));
128
+ * this.currentSong = this.playlist.head;
129
+ * }
130
+ *
131
+ * // Play the next song in the playlist
132
+ * playNext(): Song | undefined {
133
+ * if (!this.currentSong?.next) {
134
+ * this.currentSong = this.playlist.head; // Loop to the first song
135
+ * } else {
136
+ * this.currentSong = this.currentSong.next;
137
+ * }
138
+ * return this.currentSong?.value;
139
+ * }
140
+ *
141
+ * // Play the previous song in the playlist
142
+ * playPrevious(): Song | undefined {
143
+ * if (!this.currentSong?.prev) {
144
+ * this.currentSong = this.playlist.tail; // Loop to the last song
145
+ * } else {
146
+ * this.currentSong = this.currentSong.prev;
147
+ * }
148
+ * return this.currentSong?.value;
149
+ * }
150
+ *
151
+ * // Get the current song
152
+ * getCurrentSong(): Song | undefined {
153
+ * return this.currentSong?.value;
154
+ * }
155
+ *
156
+ * // Loop through the playlist twice
157
+ * loopThroughPlaylist(): Song[] {
158
+ * const playedSongs: Song[] = [];
159
+ * const initialNode = this.currentSong;
160
+ *
161
+ * // Loop through the playlist twice
162
+ * for (let i = 0; i < this.playlist.size * 2; i++) {
163
+ * playedSongs.push(this.currentSong!.value);
164
+ * this.currentSong = this.currentSong!.next || this.playlist.head; // Loop back to the start if needed
165
+ * }
166
+ *
167
+ * // Reset the current song to the initial song
168
+ * this.currentSong = initialNode;
169
+ * return playedSongs;
170
+ * }
171
+ * }
172
+ *
173
+ * const songs = [
174
+ * { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
175
+ * { title: 'Hotel California', artist: 'Eagles', duration: 391 },
176
+ * { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
177
+ * { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
178
+ * ];
179
+ * let player = new Player(songs);
180
+ * // should play the next song
181
+ * player = new Player(songs);
182
+ * const firstSong = player.getCurrentSong();
183
+ * const nextSong = player.playNext();
184
+ *
185
+ * // Expect the next song to be "Hotel California by Eagles"
186
+ * console.log(nextSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }
187
+ * console.log(firstSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
188
+ *
189
+ * // should play the previous song
190
+ * player = new Player(songs);
191
+ * player.playNext(); // Move to the second song
192
+ * const currentSong = player.getCurrentSong();
193
+ * const previousSong = player.playPrevious();
194
+ *
195
+ * // Expect the previous song to be "Bohemian Rhapsody by Queen"
196
+ * console.log(previousSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
197
+ * console.log(currentSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }
198
+ *
199
+ * // should loop to the first song when playing next from the last song
200
+ * player = new Player(songs);
201
+ * player.playNext(); // Move to the second song
202
+ * player.playNext(); // Move to the third song
203
+ * player.playNext(); // Move to the fourth song
204
+ *
205
+ * const nextSongToFirst = player.playNext(); // Should loop to the first song
206
+ *
207
+ * // Expect the next song to be "Bohemian Rhapsody by Queen"
208
+ * console.log(nextSongToFirst); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
209
+ *
210
+ * // should loop to the last song when playing previous from the first song
211
+ * player = new Player(songs);
212
+ * player.playNext(); // Move to the first song
213
+ * player.playNext(); // Move to the second song
214
+ * player.playNext(); // Move to the third song
215
+ * player.playNext(); // Move to the fourth song
216
+ *
217
+ * const previousToLast = player.playPrevious(); // Should loop to the last song
218
+ *
219
+ * // Expect the previous song to be "Billie Jean by Michael Jackson"
220
+ * console.log(previousToLast); // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
221
+ *
222
+ * // should loop through the entire playlist
223
+ * player = new Player(songs);
224
+ * const playedSongs = player.loopThroughPlaylist();
225
+ *
226
+ * // The expected order of songs for two loops
227
+ * console.log(playedSongs); // [
228
+ * // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
229
+ * // { title: 'Hotel California', artist: 'Eagles', duration: 391 },
230
+ * // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
231
+ * // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 },
232
+ * // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
233
+ * // { title: 'Hotel California', artist: 'Eagles', duration: 391 },
234
+ * // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
235
+ * // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
236
+ * // ]
237
+ * @example
238
+ * // Use DoublyLinkedList to implement LRU cache
239
+ * interface CacheEntry<K, V> {
240
+ * key: K;
241
+ * value: V;
242
+ * }
243
+ *
244
+ * class LRUCache<K = string, V = any> {
245
+ * private readonly capacity: number;
246
+ * private list: DoublyLinkedList<CacheEntry<K, V>>;
247
+ * private map: Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>;
248
+ *
249
+ * constructor(capacity: number) {
250
+ * if (capacity <= 0) {
251
+ * throw new Error('lru cache capacity must be greater than 0');
252
+ * }
253
+ * this.capacity = capacity;
254
+ * this.list = new DoublyLinkedList<CacheEntry<K, V>>();
255
+ * this.map = new Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>();
256
+ * }
257
+ *
258
+ * // Get cached value
259
+ * get(key: K): V | undefined {
260
+ * const node = this.map.get(key);
261
+ *
262
+ * if (!node) return undefined;
263
+ *
264
+ * // Move the visited node to the head of the linked list (most recently used)
265
+ * this.moveToFront(node);
266
+ *
267
+ * return node.value.value;
268
+ * }
269
+ *
270
+ * // Set cache value
271
+ * set(key: K, value: V): void {
272
+ * // Check if it already exists
273
+ * const node = this.map.get(key);
274
+ *
275
+ * if (node) {
276
+ * // Update value and move to head
277
+ * node.value.value = value;
278
+ * this.moveToFront(node);
279
+ * return;
280
+ * }
281
+ *
282
+ * // Check capacity
283
+ * if (this.list.size >= this.capacity) {
284
+ * // Delete the least recently used element (the tail of the linked list)
285
+ * const removedNode = this.list.tail;
286
+ * if (removedNode) {
287
+ * this.map.delete(removedNode.value.key);
288
+ * this.list.pop();
289
+ * }
290
+ * }
291
+ *
292
+ * // Create new node and add to head
293
+ * const newEntry: CacheEntry<K, V> = { key, value };
294
+ * this.list.unshift(newEntry);
295
+ *
296
+ * // Save node reference in map
297
+ * const newNode = this.list.head;
298
+ * if (newNode) {
299
+ * this.map.set(key, newNode);
300
+ * }
301
+ * }
302
+ *
303
+ * // Move the node to the head of the linked list
304
+ * private moveToFront(node: DoublyLinkedListNode<CacheEntry<K, V>>): void {
305
+ * this.list.delete(node);
306
+ * this.list.unshift(node.value);
307
+ * }
308
+ *
309
+ * // Delete specific key
310
+ * delete(key: K): boolean {
311
+ * const node = this.map.get(key);
312
+ * if (!node) return false;
313
+ *
314
+ * // Remove from linked list
315
+ * this.list.delete(node);
316
+ * // Remove from map
317
+ * this.map.delete(key);
318
+ *
319
+ * return true;
320
+ * }
321
+ *
322
+ * // Clear cache
323
+ * clear(): void {
324
+ * this.list.clear();
325
+ * this.map.clear();
326
+ * }
327
+ *
328
+ * // Get the current cache size
329
+ * get size(): number {
330
+ * return this.list.size;
331
+ * }
332
+ *
333
+ * // Check if it is empty
334
+ * get isEmpty(): boolean {
335
+ * return this.list.isEmpty();
336
+ * }
337
+ * }
338
+ *
339
+ * // should set and get values correctly
340
+ * const cache = new LRUCache<string, number>(3);
341
+ * cache.set('a', 1);
342
+ * cache.set('b', 2);
343
+ * cache.set('c', 3);
344
+ *
345
+ * console.log(cache.get('a')); // 1
346
+ * console.log(cache.get('b')); // 2
347
+ * console.log(cache.get('c')); // 3
348
+ *
349
+ * // The least recently used element should be evicted when capacity is exceeded
350
+ * cache.clear();
351
+ * cache.set('a', 1);
352
+ * cache.set('b', 2);
353
+ * cache.set('c', 3);
354
+ * cache.set('d', 4); // This will eliminate 'a'
355
+ *
356
+ * console.log(cache.get('a')); // undefined
357
+ * console.log(cache.get('b')); // 2
358
+ * console.log(cache.get('c')); // 3
359
+ * console.log(cache.get('d')); // 4
360
+ *
361
+ * // The priority of an element should be updated when it is accessed
362
+ * cache.clear();
363
+ * cache.set('a', 1);
364
+ * cache.set('b', 2);
365
+ * cache.set('c', 3);
366
+ *
367
+ * cache.get('a'); // access 'a'
368
+ * cache.set('d', 4); // This will eliminate 'b'
369
+ *
370
+ * console.log(cache.get('a')); // 1
371
+ * console.log(cache.get('b')); // undefined
372
+ * console.log(cache.get('c')); // 3
373
+ * console.log(cache.get('d')); // 4
374
+ *
375
+ * // Should support updating existing keys
376
+ * cache.clear();
377
+ * cache.set('a', 1);
378
+ * cache.set('a', 10);
379
+ *
380
+ * console.log(cache.get('a')); // 10
381
+ *
382
+ * // Should support deleting specified keys
383
+ * cache.clear();
384
+ * cache.set('a', 1);
385
+ * cache.set('b', 2);
386
+ *
387
+ * console.log(cache.delete('a')); // true
388
+ * console.log(cache.get('a')); // undefined
389
+ * console.log(cache.size); // 1
390
+ *
391
+ * // Should support clearing cache
392
+ * cache.clear();
393
+ * cache.set('a', 1);
394
+ * cache.set('b', 2);
395
+ * cache.clear();
396
+ *
397
+ * console.log(cache.size); // 0
398
+ * console.log(cache.isEmpty); // true
399
+ * @example
400
+ * // finding lyrics by timestamp in Coldplay's "Fix You"
401
+ * // Create a DoublyLinkedList to store song lyrics with timestamps
402
+ * const lyricsList = new DoublyLinkedList<{ time: number; text: string }>();
403
+ *
404
+ * // Detailed lyrics with precise timestamps (in milliseconds)
405
+ * const lyrics = [
406
+ * { time: 0, text: "When you try your best, but you don't succeed" },
407
+ * { time: 4000, text: 'When you get what you want, but not what you need' },
408
+ * { time: 8000, text: "When you feel so tired, but you can't sleep" },
409
+ * { time: 12000, text: 'Stuck in reverse' },
410
+ * { time: 16000, text: 'And the tears come streaming down your face' },
411
+ * { time: 20000, text: "When you lose something you can't replace" },
412
+ * { time: 24000, text: 'When you love someone, but it goes to waste' },
413
+ * { time: 28000, text: 'Could it be worse?' },
414
+ * { time: 32000, text: 'Lights will guide you home' },
415
+ * { time: 36000, text: 'And ignite your bones' },
416
+ * { time: 40000, text: 'And I will try to fix you' }
417
+ * ];
418
+ *
419
+ * // Populate the DoublyLinkedList with lyrics
420
+ * lyrics.forEach(lyric => lyricsList.push(lyric));
421
+ *
422
+ * // Test different scenarios of lyric synchronization
423
+ *
424
+ * // 1. Find lyric at exact timestamp
425
+ * const exactTimeLyric = lyricsList.findBackward(lyric => lyric.time <= 36000);
426
+ * console.log(exactTimeLyric?.text); // 'And ignite your bones'
427
+ *
428
+ * // 2. Find lyric between timestamps
429
+ * const betweenTimeLyric = lyricsList.findBackward(lyric => lyric.time <= 22000);
430
+ * console.log(betweenTimeLyric?.text); // "When you lose something you can't replace"
431
+ *
432
+ * // 3. Find first lyric when timestamp is less than first entry
433
+ * const earlyTimeLyric = lyricsList.findBackward(lyric => lyric.time <= -1000);
434
+ * console.log(earlyTimeLyric); // undefined
435
+ *
436
+ * // 4. Find last lyric when timestamp is after last entry
437
+ * const lateTimeLyric = lyricsList.findBackward(lyric => lyric.time <= 50000);
438
+ * console.log(lateTimeLyric?.text); // 'And I will try to fix you'
439
+ * @example
440
+ * // cpu process schedules
441
+ * class Process {
442
+ * constructor(
443
+ * public id: number,
444
+ * public priority: number
445
+ * ) {}
446
+ *
447
+ * execute(): string {
448
+ * return `Process ${this.id} executed.`;
449
+ * }
450
+ * }
451
+ *
452
+ * class Scheduler {
453
+ * private queue: DoublyLinkedList<Process>;
454
+ *
455
+ * constructor() {
456
+ * this.queue = new DoublyLinkedList<Process>();
457
+ * }
458
+ *
459
+ * addProcess(process: Process): void {
460
+ * // Insert processes into a queue based on priority, keeping priority in descending order
461
+ * let current = this.queue.head;
462
+ * while (current && current.value.priority >= process.priority) {
463
+ * current = current.next;
464
+ * }
465
+ *
466
+ * if (!current) {
467
+ * this.queue.push(process);
468
+ * } else {
469
+ * this.queue.addBefore(current, process);
470
+ * }
471
+ * }
472
+ *
473
+ * executeNext(): string | undefined {
474
+ * // Execute tasks at the head of the queue in order
475
+ * const process = this.queue.shift();
476
+ * return process ? process.execute() : undefined;
477
+ * }
478
+ *
479
+ * listProcesses(): string[] {
480
+ * return this.queue.toArray().map(process => `Process ${process.id} (Priority: ${process.priority})`);
481
+ * }
482
+ *
483
+ * clear(): void {
484
+ * this.queue.clear();
485
+ * }
486
+ * }
487
+ *
488
+ * // should add processes based on priority
489
+ * let scheduler = new Scheduler();
490
+ * scheduler.addProcess(new Process(1, 10));
491
+ * scheduler.addProcess(new Process(2, 20));
492
+ * scheduler.addProcess(new Process(3, 15));
493
+ *
494
+ * console.log(scheduler.listProcesses()); // [
495
+ * // 'Process 2 (Priority: 20)',
496
+ * // 'Process 3 (Priority: 15)',
497
+ * // 'Process 1 (Priority: 10)'
498
+ * // ]
499
+ *
500
+ * // should execute the highest priority process
501
+ * scheduler = new Scheduler();
502
+ * scheduler.addProcess(new Process(1, 10));
503
+ * scheduler.addProcess(new Process(2, 20));
504
+ *
505
+ * console.log(scheduler.executeNext()); // 'Process 2 executed.'
506
+ * console.log(scheduler.listProcesses()); // ['Process 1 (Priority: 10)']
507
+ *
508
+ * // should clear all processes
509
+ * scheduler = new Scheduler();
510
+ * scheduler.addProcess(new Process(1, 10));
511
+ * scheduler.addProcess(new Process(2, 20));
512
+ *
513
+ * scheduler.clear();
514
+ * console.log(scheduler.listProcesses()); // []
89
515
  */
90
516
  export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R, DoublyLinkedList<E, R>> {
91
517
  constructor(elements: Iterable<E> | Iterable<R> = [], options?: DoublyLinkedListOptions<E, R>) {
@@ -488,8 +914,8 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
488
914
  } else {
489
915
  const prevNode = node.prev;
490
916
  const nextNode = node.next;
491
- prevNode!.next = nextNode;
492
- nextNode!.prev = prevNode;
917
+ if (prevNode) prevNode.next = nextNode;
918
+ if (nextNode) nextNode.prev = prevNode;
493
919
  this._size--;
494
920
  }
495
921
  return true;