linked-list-typed 1.53.4 → 1.53.6

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