Compare commits

..

No commits in common. "fde5af1f1c8c550b08057662f9604732bd4c33e3" and "476395ef7220b1fa3201e79ed42e2b2f37a941e9" have entirely different histories.

11 changed files with 236 additions and 1952 deletions

View file

@ -8,7 +8,7 @@ All notable changes to this project will be documented in this file.
- [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
- [`auto-changelog`](https://github.com/CookPete/auto-changelog)
## [v1.53.5](https://github.com/zrwusa/data-structure-typed/compare/v1.51.5...main) (upcoming)
## [v1.53.1](https://github.com/zrwusa/data-structure-typed/compare/v1.51.5...main) (upcoming)
### Changes

View file

@ -798,12 +798,6 @@ Array.from(dijkstraResult?.seen ?? []).map(vertex => vertex.key) // ['A', 'B', '
```
[//]: # (No deletion!!! Start of Example Replace Section)
[//]: # (No deletion!!! End of Example Replace Section)
## API docs & Examples
[API Docs](https://data-structure-typed-docs.vercel.app)

52
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "data-structure-typed",
"version": "1.53.5",
"version": "1.53.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "data-structure-typed",
"version": "1.53.5",
"version": "1.53.1",
"license": "MIT",
"devDependencies": {
"@eslint/compat": "^1.2.2",
@ -19,11 +19,11 @@
"@typescript-eslint/eslint-plugin": "^8.12.1",
"@typescript-eslint/parser": "^8.12.1",
"auto-changelog": "^2.5.0",
"avl-tree-typed": "^1.53.4",
"avl-tree-typed": "^1.53.0",
"benchmark": "^2.1.4",
"binary-tree-typed": "^1.53.4",
"bst-typed": "^1.53.4",
"data-structure-typed": "^1.53.4",
"binary-tree-typed": "^1.53.0",
"bst-typed": "^1.53.0",
"data-structure-typed": "^1.53.0",
"dependency-cruiser": "^16.5.0",
"doctoc": "^2.2.1",
"eslint": "^9.13.0",
@ -32,7 +32,7 @@
"eslint-import-resolver-typescript": "^3.6.3",
"eslint-plugin-import": "^2.31.0",
"fast-glob": "^3.3.2",
"heap-typed": "^1.53.4",
"heap-typed": "^1.53.0",
"istanbul-badges-readme": "^1.9.0",
"jest": "^29.7.0",
"js-sdsl": "^4.4.2",
@ -3437,13 +3437,13 @@
}
},
"node_modules/avl-tree-typed": {
"version": "1.53.4",
"resolved": "https://registry.npmjs.org/avl-tree-typed/-/avl-tree-typed-1.53.4.tgz",
"integrity": "sha512-dZMEutl5xMp/n54V6W6SugCXdmfcgy+6esqlpjG47nQfrQ3WMQzx2oytMWRZa6Y+nDtDNefbwlEOO/fLKZUHyQ==",
"version": "1.53.0",
"resolved": "https://registry.npmjs.org/avl-tree-typed/-/avl-tree-typed-1.53.0.tgz",
"integrity": "sha512-SVk6zEvzrB2GhHVFOhVO2yaB7p9iLGy2aml0j7UW1rWp+VACw4SZQhKuldl2qC7ECb9AOIbajD7Y9ott8Qfy8Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"data-structure-typed": "^1.53.4"
"data-structure-typed": "^1.53.0"
}
},
"node_modules/babel-jest": {
@ -3602,13 +3602,13 @@
}
},
"node_modules/binary-tree-typed": {
"version": "1.53.4",
"resolved": "https://registry.npmjs.org/binary-tree-typed/-/binary-tree-typed-1.53.4.tgz",
"integrity": "sha512-/yDQUWHdT1HQBkMVTGZuo+Nn/nx1JnV5ERBFIKCdDVBvG2qKmTa5RlSC7rnjLzLsQz28qVHvisjoRYBhcQpCWg==",
"version": "1.53.0",
"resolved": "https://registry.npmjs.org/binary-tree-typed/-/binary-tree-typed-1.53.0.tgz",
"integrity": "sha512-5EmlwbR4Kaphual+wF2rJwpZFhhK2u6zOFiA+yagWDbH6tzBCojT5o2DN+1tmW1Pj6bGJxz7PHcDBIdBkQruMw==",
"dev": true,
"license": "MIT",
"dependencies": {
"data-structure-typed": "^1.53.4"
"data-structure-typed": "^1.53.0"
}
},
"node_modules/brace-expansion": {
@ -3691,13 +3691,13 @@
}
},
"node_modules/bst-typed": {
"version": "1.53.4",
"resolved": "https://registry.npmjs.org/bst-typed/-/bst-typed-1.53.4.tgz",
"integrity": "sha512-hjTK/CcW2hw0yAtazhFOl7lsNq598FuNwCgbcjpFgXk51swLwJ5P5Sm70UzwVns1LSdIulTK49zil9tGs6zv1g==",
"version": "1.53.0",
"resolved": "https://registry.npmjs.org/bst-typed/-/bst-typed-1.53.0.tgz",
"integrity": "sha512-f1f+RlbIA6J2reFO/DwLRLaZVBmMNNyKCi5eWd+r5ojV9bDC/IZ34nzID0zSJUwVqtAtIpaK9x63XAo42+5SoQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"data-structure-typed": "^1.53.4"
"data-structure-typed": "^1.53.0"
}
},
"node_modules/buffer-from": {
@ -4069,9 +4069,9 @@
}
},
"node_modules/data-structure-typed": {
"version": "1.53.4",
"resolved": "https://registry.npmjs.org/data-structure-typed/-/data-structure-typed-1.53.4.tgz",
"integrity": "sha512-sMmlWv2wMqUVPnBemYc7RQMYtM0AXQq0m9drVeu0eMtpSvojvFb4hW+hzpd6IBtULguNw2YBG9EyNo7irlpavQ==",
"version": "1.53.0",
"resolved": "https://registry.npmjs.org/data-structure-typed/-/data-structure-typed-1.53.0.tgz",
"integrity": "sha512-bukacSwbWyypNTdQCt51rwNcqM1hacHG6mMJ2RDBqsz8jJ5N4oMOgQhDyA1GkvMvdq83mcj9ilCFZ6lDcwShqA==",
"dev": true,
"license": "MIT"
},
@ -5946,13 +5946,13 @@
}
},
"node_modules/heap-typed": {
"version": "1.53.4",
"resolved": "https://registry.npmjs.org/heap-typed/-/heap-typed-1.53.4.tgz",
"integrity": "sha512-/lktvgpfH7Y2q8XpMFYCEebRIo5nM85DCR19zUeo3soVrxa2H90vJAKJJ0cPP/DEJ2cDggMk/Cuo4k4LLhbf7A==",
"version": "1.53.0",
"resolved": "https://registry.npmjs.org/heap-typed/-/heap-typed-1.53.0.tgz",
"integrity": "sha512-MtbVdNGb2mvLrv67j0ajaMDr/u0HpR0tMaCj1MUrmXKK+IhVqniq7I8ADUlDrEPpKXwES8RBa0v7lA5umKR9hg==",
"dev": true,
"license": "MIT",
"dependencies": {
"data-structure-typed": "^1.53.4"
"data-structure-typed": "^1.53.0"
}
},
"node_modules/html-escaper": {

View file

@ -1,6 +1,6 @@
{
"name": "data-structure-typed",
"version": "1.53.5",
"version": "1.53.2",
"description": "Javascript Data Structure. Heap, Binary Tree, Red Black Tree, Linked List, Deque, Trie, HashMap, Directed Graph, Undirected Graph, Binary Search Tree(BST), AVL Tree, Priority Queue, Graph, Queue, Tree Multiset, Singly Linked List, Doubly Linked List, Max Heap, Max Priority Queue, Min Heap, Min Priority Queue, Stack. Benchmark compared with C++ STL. API aligned with ES6 and Java.util. Usability is comparable to Python",
"main": "dist/cjs/index.js",
"module": "dist/mjs/index.js",
@ -18,11 +18,10 @@
"build:mjs": "rm -rf dist/mjs && tsc -p tsconfig-mjs.json",
"build:cjs": "rm -rf dist/cjs && tsc -p tsconfig-cjs.json",
"build:umd": "tsup",
"build:docs": "npm run gen:examples && typedoc --out docs ./src",
"build:docs-class": "npm run gen:examples && typedoc --out docs ./src/data-structures",
"gen:examples": "ts-node testToExample.ts",
"test:in-band": "jest --runInBand",
"test": "npm run test:in-band",
"build:docs": "typedoc --out docs ./src",
"build:docs-class": "typedoc --out docs ./src/data-structures",
"test:unit": "jest --runInBand",
"test": "npm run test:unit",
"test:integration": "npm run update:subs && jest --config jest.integration.config.js",
"test:perf": "npm run build:cjs && npm run build:mjs && ts-node test/performance/reportor.ts",
"check": "tsc --noEmit",
@ -35,7 +34,7 @@
"format:test": "prettier --write 'test/**/*.{js,ts}'",
"format": "npm run format:src && npm run format:test",
"check:exist-latest": "sh scripts/check_exist_remotely.sh",
"ci": "env && git fetch --tags && npm run update:subs && npm run inspect && npm run lint && npm run build && npm run test && npm run changelog",
"ci": "env && git fetch --tags && npm run update:subs && npm run inspect && npm run lint && npm run build && npm run test:unit && npm run changelog",
"update:subs": "npm i avl-tree-typed binary-tree-typed bst-typed heap-typed data-structure-typed --save-dev",
"install:all-subs": "npm i avl-tree-typed binary-tree-typed bst-typed deque-typed directed-graph-typed doubly-linked-list-typed graph-typed heap-typed linked-list-typed max-heap-typed max-priority-queue-typed min-heap-typed min-priority-queue-typed priority-queue-typed singly-linked-list-typed stack-typed tree-multimap-typed trie-typed undirected-graph-typed queue-typed --save-dev",
"changelog": "auto-changelog",
@ -70,11 +69,11 @@
"@typescript-eslint/eslint-plugin": "^8.12.1",
"@typescript-eslint/parser": "^8.12.1",
"auto-changelog": "^2.5.0",
"avl-tree-typed": "^1.53.4",
"avl-tree-typed": "^1.53.0",
"benchmark": "^2.1.4",
"binary-tree-typed": "^1.53.4",
"bst-typed": "^1.53.4",
"data-structure-typed": "^1.53.4",
"binary-tree-typed": "^1.53.0",
"bst-typed": "^1.53.0",
"data-structure-typed": "^1.53.0",
"dependency-cruiser": "^16.5.0",
"doctoc": "^2.2.1",
"eslint": "^9.13.0",
@ -83,7 +82,7 @@
"eslint-import-resolver-typescript": "^3.6.3",
"eslint-plugin-import": "^2.31.0",
"fast-glob": "^3.3.2",
"heap-typed": "^1.53.4",
"heap-typed": "^1.53.0",
"istanbul-badges-readme": "^1.9.0",
"jest": "^29.7.0",
"js-sdsl": "^4.4.2",

View file

@ -19,171 +19,6 @@ import { IterableElementBase } from '../base';
* 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.
* 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.
* 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prime's minimum-spanning tree algorithm, which use heaps to improve performance.
* @example
* // Use Heap to sort an array
* function heapSort(arr: number[]): number[] {
* const heap = new Heap<number>(arr, { comparator: (a, b) => a - b });
* const sorted: number[] = [];
* while (!heap.isEmpty()) {
* sorted.push(heap.poll()!); // Poll minimum element
* }
* return sorted;
* }
*
* const array = [5, 3, 8, 4, 1, 2];
* console.log(heapSort(array)); // [1, 2, 3, 4, 5, 8]
* @example
* // Use Heap to solve top k problems
* function topKElements(arr: number[], k: number): number[] {
* const heap = new Heap<number>([], { comparator: (a, b) => b - a }); // Max heap
* arr.forEach(num => {
* heap.add(num);
* if (heap.size > k) heap.poll(); // Keep the heap size at K
* });
* return heap.toArray();
* }
*
* const numbers = [10, 30, 20, 5, 15, 25];
* console.log(topKElements(numbers, 3)); // [15, 10, 5]
* @example
* // Use Heap to merge sorted sequences
* function mergeSortedSequences(sequences: number[][]): number[] {
* const heap = new Heap<{ value: number; seqIndex: number; itemIndex: number }>([], {
* comparator: (a, b) => a.value - b.value // Min heap
* });
*
* // Initialize heap
* sequences.forEach((seq, seqIndex) => {
* if (seq.length) {
* heap.add({ value: seq[0], seqIndex, itemIndex: 0 });
* }
* });
*
* const merged: number[] = [];
* while (!heap.isEmpty()) {
* const { value, seqIndex, itemIndex } = heap.poll()!;
* merged.push(value);
*
* if (itemIndex + 1 < sequences[seqIndex].length) {
* heap.add({
* value: sequences[seqIndex][itemIndex + 1],
* seqIndex,
* itemIndex: itemIndex + 1
* });
* }
* }
*
* return merged;
* }
*
* const sequences = [
* [1, 4, 7],
* [2, 5, 8],
* [3, 6, 9]
* ];
* console.log(mergeSortedSequences(sequences)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
* @example
* // Use Heap to dynamically maintain the median
* class MedianFinder {
* private low: MaxHeap<number>; // Max heap, stores the smaller half
* private high: MinHeap<number>; // Min heap, stores the larger half
*
* constructor() {
* this.low = new MaxHeap<number>([]);
* this.high = new MinHeap<number>([]);
* }
*
* addNum(num: number): void {
* if (this.low.isEmpty() || num <= this.low.peek()!) this.low.add(num);
* else this.high.add(num);
*
* // Balance heaps
* if (this.low.size > this.high.size + 1) this.high.add(this.low.poll()!);
* else if (this.high.size > this.low.size) this.low.add(this.high.poll()!);
* }
*
* findMedian(): number {
* if (this.low.size === this.high.size) return (this.low.peek()! + this.high.peek()!) / 2;
* return this.low.peek()!;
* }
* }
*
* const medianFinder = new MedianFinder();
* medianFinder.addNum(10);
* console.log(medianFinder.findMedian()); // 10
* medianFinder.addNum(20);
* console.log(medianFinder.findMedian()); // 15
* medianFinder.addNum(30);
* console.log(medianFinder.findMedian()); // 20
* medianFinder.addNum(40);
* console.log(medianFinder.findMedian()); // 25
* medianFinder.addNum(50);
* console.log(medianFinder.findMedian()); // 30
* @example
* // Use Heap for load balancing
* function loadBalance(requests: number[], servers: number): number[] {
* const serverHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // min heap
* const serverLoads = new Array(servers).fill(0);
*
* for (let i = 0; i < servers; i++) {
* serverHeap.add({ id: i, load: 0 });
* }
*
* requests.forEach(req => {
* const server = serverHeap.poll()!;
* serverLoads[server.id] += req;
* server.load += req;
* serverHeap.add(server); // The server after updating the load is re-entered into the heap
* });
*
* return serverLoads;
* }
*
* const requests = [5, 2, 8, 3, 7];
* console.log(loadBalance(requests, 3)); // [12, 8, 5]
* @example
* // Use Heap to schedule tasks
* type Task = [string, number];
*
* function scheduleTasks(tasks: Task[], machines: number): Map<number, Task[]> {
* const machineHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // Min heap
* const allocation = new Map<number, Task[]>();
*
* // Initialize the load on each machine
* for (let i = 0; i < machines; i++) {
* machineHeap.add({ id: i, load: 0 });
* allocation.set(i, []);
* }
*
* // Assign tasks
* tasks.forEach(([task, load]) => {
* const machine = machineHeap.poll()!;
* allocation.get(machine.id)!.push([task, load]);
* machine.load += load;
* machineHeap.add(machine); // The machine after updating the load is re-entered into the heap
* });
*
* return allocation;
* }
*
* const tasks: Task[] = [
* ['Task1', 3],
* ['Task2', 1],
* ['Task3', 2],
* ['Task4', 5],
* ['Task5', 4]
* ];
* const expectedMap = new Map<number, Task[]>();
* expectedMap.set(0, [
* ['Task1', 3],
* ['Task4', 5]
* ]);
* expectedMap.set(1, [
* ['Task2', 1],
* ['Task3', 2],
* ['Task5', 4]
* ]);
* console.log(scheduleTasks(tasks, 2)); // expectedMap
*/
export class Heap<E = any, R = any> extends IterableElementBase<E, R, Heap<E, R>> {
/**

View file

@ -86,432 +86,6 @@ export class DoublyLinkedListNode<E = any> {
* 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.
* 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.
* 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.
* @example
* // text editor operation history
* const actions = [
* { type: 'insert', content: 'first line of text' },
* { type: 'insert', content: 'second line of text' },
* { type: 'delete', content: 'delete the first line' }
* ];
* const editorHistory = new DoublyLinkedList<{ type: string; content: string }>(actions);
*
* console.log(editorHistory.last?.type); // 'delete'
* console.log(editorHistory.pop()?.content); // 'delete the first line'
* console.log(editorHistory.last?.type); // 'insert'
* @example
* // Browser history
* const browserHistory = new DoublyLinkedList<string>();
*
* browserHistory.push('home page');
* browserHistory.push('search page');
* browserHistory.push('details page');
*
* console.log(browserHistory.last); // 'details page'
* console.log(browserHistory.pop()); // 'details page'
* console.log(browserHistory.last); // 'search page'
* @example
* // Use DoublyLinkedList to implement music player
* // Define the Song interface
* interface Song {
* title: string;
* artist: string;
* duration: number; // duration in seconds
* }
*
* class Player {
* private playlist: DoublyLinkedList<Song>;
* private currentSong: ReturnType<typeof this.playlist.getNodeAt> | undefined;
*
* constructor(songs: Song[]) {
* this.playlist = new DoublyLinkedList<Song>();
* songs.forEach(song => this.playlist.push(song));
* this.currentSong = this.playlist.head;
* }
*
* // Play the next song in the playlist
* playNext(): Song | undefined {
* if (!this.currentSong?.next) {
* this.currentSong = this.playlist.head; // Loop to the first song
* } else {
* this.currentSong = this.currentSong.next;
* }
* return this.currentSong?.value;
* }
*
* // Play the previous song in the playlist
* playPrevious(): Song | undefined {
* if (!this.currentSong?.prev) {
* this.currentSong = this.playlist.tail; // Loop to the last song
* } else {
* this.currentSong = this.currentSong.prev;
* }
* return this.currentSong?.value;
* }
*
* // Get the current song
* getCurrentSong(): Song | undefined {
* return this.currentSong?.value;
* }
*
* // Loop through the playlist twice
* loopThroughPlaylist(): Song[] {
* const playedSongs: Song[] = [];
* const initialNode = this.currentSong;
*
* // Loop through the playlist twice
* for (let i = 0; i < this.playlist.size * 2; i++) {
* playedSongs.push(this.currentSong!.value);
* this.currentSong = this.currentSong!.next || this.playlist.head; // Loop back to the start if needed
* }
*
* // Reset the current song to the initial song
* this.currentSong = initialNode;
* return playedSongs;
* }
* }
*
* const songs = [
* { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
* { title: 'Hotel California', artist: 'Eagles', duration: 391 },
* { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
* { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
* ];
* let player = new Player(songs);
* // should play the next song
* player = new Player(songs);
* const firstSong = player.getCurrentSong();
* const nextSong = player.playNext();
*
* // Expect the next song to be "Hotel California by Eagles"
* console.log(nextSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }
* console.log(firstSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
*
* // should play the previous song
* player = new Player(songs);
* player.playNext(); // Move to the second song
* const currentSong = player.getCurrentSong();
* const previousSong = player.playPrevious();
*
* // Expect the previous song to be "Bohemian Rhapsody by Queen"
* console.log(previousSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
* console.log(currentSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }
*
* // should loop to the first song when playing next from the last song
* player = new Player(songs);
* player.playNext(); // Move to the second song
* player.playNext(); // Move to the third song
* player.playNext(); // Move to the fourth song
*
* const nextSongToFirst = player.playNext(); // Should loop to the first song
*
* // Expect the next song to be "Bohemian Rhapsody by Queen"
* console.log(nextSongToFirst); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
*
* // should loop to the last song when playing previous from the first song
* player = new Player(songs);
* player.playNext(); // Move to the first song
* player.playNext(); // Move to the second song
* player.playNext(); // Move to the third song
* player.playNext(); // Move to the fourth song
*
* const previousToLast = player.playPrevious(); // Should loop to the last song
*
* // Expect the previous song to be "Billie Jean by Michael Jackson"
* console.log(previousToLast); // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
*
* // should loop through the entire playlist
* player = new Player(songs);
* const playedSongs = player.loopThroughPlaylist();
*
* // The expected order of songs for two loops
* console.log(playedSongs); // [
* // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
* // { title: 'Hotel California', artist: 'Eagles', duration: 391 },
* // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
* // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 },
* // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
* // { title: 'Hotel California', artist: 'Eagles', duration: 391 },
* // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
* // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
* // ]
* @example
* // Use DoublyLinkedList to implement LRU cache
* interface CacheEntry<K, V> {
* key: K;
* value: V;
* }
*
* class LRUCache<K = string, V = any> {
* private readonly capacity: number;
* private list: DoublyLinkedList<CacheEntry<K, V>>;
* private map: Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>;
*
* constructor(capacity: number) {
* if (capacity <= 0) {
* throw new Error('lru cache capacity must be greater than 0');
* }
* this.capacity = capacity;
* this.list = new DoublyLinkedList<CacheEntry<K, V>>();
* this.map = new Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>();
* }
*
* // Get cached value
* get(key: K): V | undefined {
* const node = this.map.get(key);
*
* if (!node) return undefined;
*
* // Move the visited node to the head of the linked list (most recently used)
* this.moveToFront(node);
*
* return node.value.value;
* }
*
* // Set cache value
* set(key: K, value: V): void {
* // Check if it already exists
* const node = this.map.get(key);
*
* if (node) {
* // Update value and move to head
* node.value.value = value;
* this.moveToFront(node);
* return;
* }
*
* // Check capacity
* if (this.list.size >= this.capacity) {
* // Delete the least recently used element (the tail of the linked list)
* const removedNode = this.list.tail;
* if (removedNode) {
* this.map.delete(removedNode.value.key);
* this.list.pop();
* }
* }
*
* // Create new node and add to head
* const newEntry: CacheEntry<K, V> = { key, value };
* this.list.unshift(newEntry);
*
* // Save node reference in map
* const newNode = this.list.head;
* if (newNode) {
* this.map.set(key, newNode);
* }
* }
*
* // Move the node to the head of the linked list
* private moveToFront(node: DoublyLinkedListNode<CacheEntry<K, V>>): void {
* this.list.delete(node);
* this.list.unshift(node.value);
* }
*
* // Delete specific key
* delete(key: K): boolean {
* const node = this.map.get(key);
* if (!node) return false;
*
* // Remove from linked list
* this.list.delete(node);
* // Remove from map
* this.map.delete(key);
*
* return true;
* }
*
* // Clear cache
* clear(): void {
* this.list.clear();
* this.map.clear();
* }
*
* // Get the current cache size
* get size(): number {
* return this.list.size;
* }
*
* // Check if it is empty
* get isEmpty(): boolean {
* return this.list.isEmpty();
* }
* }
*
* // should set and get values correctly
* const cache = new LRUCache<string, number>(3);
* cache.set('a', 1);
* cache.set('b', 2);
* cache.set('c', 3);
*
* console.log(cache.get('a')); // 1
* console.log(cache.get('b')); // 2
* console.log(cache.get('c')); // 3
*
* // The least recently used element should be evicted when capacity is exceeded
* cache.clear();
* cache.set('a', 1);
* cache.set('b', 2);
* cache.set('c', 3);
* cache.set('d', 4); // This will eliminate 'a'
*
* console.log(cache.get('a')); // undefined
* console.log(cache.get('b')); // 2
* console.log(cache.get('c')); // 3
* console.log(cache.get('d')); // 4
*
* // The priority of an element should be updated when it is accessed
* cache.clear();
* cache.set('a', 1);
* cache.set('b', 2);
* cache.set('c', 3);
*
* cache.get('a'); // access 'a'
* cache.set('d', 4); // This will eliminate 'b'
*
* console.log(cache.get('a')); // 1
* console.log(cache.get('b')); // undefined
* console.log(cache.get('c')); // 3
* console.log(cache.get('d')); // 4
*
* // Should support updating existing keys
* cache.clear();
* cache.set('a', 1);
* cache.set('a', 10);
*
* console.log(cache.get('a')); // 10
*
* // Should support deleting specified keys
* cache.clear();
* cache.set('a', 1);
* cache.set('b', 2);
*
* console.log(cache.delete('a')); // true
* console.log(cache.get('a')); // undefined
* console.log(cache.size); // 1
*
* // Should support clearing cache
* cache.clear();
* cache.set('a', 1);
* cache.set('b', 2);
* cache.clear();
*
* console.log(cache.size); // 0
* console.log(cache.isEmpty); // true
* @example
* // finding lyrics by timestamp in Coldplay's "Fix You"
* // Create a DoublyLinkedList to store song lyrics with timestamps
* const lyricsList = new DoublyLinkedList<{ time: number; text: string }>();
*
* // Detailed lyrics with precise timestamps (in milliseconds)
* const lyrics = [
* { time: 0, text: "When you try your best, but you don't succeed" },
* { time: 4000, text: 'When you get what you want, but not what you need' },
* { time: 8000, text: "When you feel so tired, but you can't sleep" },
* { time: 12000, text: 'Stuck in reverse' },
* { time: 16000, text: 'And the tears come streaming down your face' },
* { time: 20000, text: "When you lose something you can't replace" },
* { time: 24000, text: 'When you love someone, but it goes to waste' },
* { time: 28000, text: 'Could it be worse?' },
* { time: 32000, text: 'Lights will guide you home' },
* { time: 36000, text: 'And ignite your bones' },
* { time: 40000, text: 'And I will try to fix you' }
* ];
*
* // Populate the DoublyLinkedList with lyrics
* lyrics.forEach(lyric => lyricsList.push(lyric));
*
* // Test different scenarios of lyric synchronization
*
* // 1. Find lyric at exact timestamp
* const exactTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 36000);
* console.log(exactTimeLyric?.text); // 'And ignite your bones'
*
* // 2. Find lyric between timestamps
* const betweenTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 22000);
* console.log(betweenTimeLyric?.text); // "When you lose something you can't replace"
*
* // 3. Find first lyric when timestamp is less than first entry
* const earlyTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= -1000);
* console.log(earlyTimeLyric); // undefined
*
* // 4. Find last lyric when timestamp is after last entry
* const lateTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 50000);
* console.log(lateTimeLyric?.text); // 'And I will try to fix you'
* @example
* // cpu process schedules
* class Process {
* constructor(
* public id: number,
* public priority: number
* ) {}
*
* execute(): string {
* return `Process ${this.id} executed.`;
* }
* }
*
* class Scheduler {
* private queue: DoublyLinkedList<Process>;
*
* constructor() {
* this.queue = new DoublyLinkedList<Process>();
* }
*
* addProcess(process: Process): void {
* // Insert processes into a queue based on priority, keeping priority in descending order
* let current = this.queue.head;
* while (current && current.value.priority >= process.priority) {
* current = current.next;
* }
*
* if (!current) {
* this.queue.push(process);
* } else {
* this.queue.addBefore(current, process);
* }
* }
*
* executeNext(): string | undefined {
* // Execute tasks at the head of the queue in order
* const process = this.queue.shift();
* return process ? process.execute() : undefined;
* }
*
* listProcesses(): string[] {
* return this.queue.toArray().map(process => `Process ${process.id} (Priority: ${process.priority})`);
* }
*
* clear(): void {
* this.queue.clear();
* }
* }
*
* // should add processes based on priority
* let scheduler = new Scheduler();
* scheduler.addProcess(new Process(1, 10));
* scheduler.addProcess(new Process(2, 20));
* scheduler.addProcess(new Process(3, 15));
*
* console.log(scheduler.listProcesses()); // [
* // 'Process 2 (Priority: 20)',
* // 'Process 3 (Priority: 15)',
* // 'Process 1 (Priority: 10)'
* // ]
*
* // should execute the highest priority process
* scheduler = new Scheduler();
* scheduler.addProcess(new Process(1, 10));
* scheduler.addProcess(new Process(2, 20));
*
* console.log(scheduler.executeNext()); // 'Process 2 executed.'
* console.log(scheduler.listProcesses()); // ['Process 1 (Priority: 10)']
*
* // should clear all processes
* scheduler = new Scheduler();
* scheduler.addProcess(new Process(1, 10));
* scheduler.addProcess(new Process(2, 20));
*
* scheduler.clear();
* console.log(scheduler.listProcesses()); // []
*/
export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R, DoublyLinkedList<E, R>> {
constructor(elements: Iterable<E> | Iterable<R> = [], options?: DoublyLinkedListOptions<E, R>) {
@ -582,36 +156,29 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
}
/**
* Time Complexity: O(1)
* Space Complexity: O(1)
* Time Complexity: O(n)
* Space Complexity: O(n)
*
* The function `isNode` in TypeScript checks if a given input is an instance of
* `DoublyLinkedListNode`.
* @param {E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)} elementNodeOrPredicate
* elementNodeOrPredicate - The `elementNodeOrPredicate` parameter in the `isNode` function can
* be one of the following types:
* @returns The `isNode` function is checking if the `elementNodeOrPredicate` parameter is an
* instance of `DoublyLinkedListNode<E>`. If it is, the function returns `true`, indicating that the
* parameter is a `DoublyLinkedListNode<E>`. If it is not an instance of `DoublyLinkedListNode<E>`,
* the function returns `false`.
* The `fromArray` function creates a new instance of a DoublyLinkedList and populates it with the elements from the
* given array.
* @param {E[]} data - The `data` parameter is an array of elements of type `E`.
* @returns The `fromArray` function returns a DoublyLinkedList object.
*/
isNode(
elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)
): elementNodeOrPredicate is DoublyLinkedListNode<E> {
return elementNodeOrPredicate instanceof DoublyLinkedListNode;
static fromArray<E>(data: E[]) {
return new DoublyLinkedList<E>(data);
}
/**
* Time Complexity: O(1)
* Space Complexity: O(1)
*
* The `push` function adds a new element or node to the end of a doubly linked list.
* @param {E | DoublyLinkedListNode<E>} elementOrNode - The `elementOrNode` parameter in the `push`
* method can accept either an element of type `E` or a `DoublyLinkedListNode<E>` object.
* @returns The `push` method is returning a boolean value, specifically `true`.
* The push function adds a new element to the end of a doubly linked list.
* @param {E} element - The "element" parameter represents the value that you want to add to the
* doubly linked list.
* @returns The `push` method is returning a boolean value, `true`.
*/
push(elementOrNode: E | DoublyLinkedListNode<E>): boolean {
const newNode = this._ensureNode(elementOrNode);
push(element: E): boolean {
const newNode = new DoublyLinkedListNode(element);
if (!this.head) {
this._head = newNode;
this._tail = newNode;
@ -670,14 +237,13 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(1)
* Space Complexity: O(1)
*
* The unshift function adds a new element or node to the beginning of a doubly linked list.
* @param {E | DoublyLinkedListNode<E>} elementOrNode - The `elementOrNode` parameter in the
* `unshift` method can be either an element of type `E` or a `DoublyLinkedListNode` containing an
* element of type `E`.
* @returns The `unshift` method is returning a boolean value, specifically `true`.
* The unshift function adds a new element to the beginning of a doubly linked list.
* @param {E} element - The "element" parameter represents the value of the element that you want to
* add to the beginning of the doubly linked list.
* @returns The `unshift` method is returning a boolean value, `true`.
*/
unshift(elementOrNode: E | DoublyLinkedListNode<E>): boolean {
const newNode = this._ensureNode(elementOrNode);
unshift(element: E): boolean {
const newNode = new DoublyLinkedListNode(element);
if (!this.head) {
this._head = newNode;
this._tail = newNode;
@ -733,29 +299,17 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* This TypeScript function searches for a node in a doubly linked list based on a given element node
* or predicate.
* @param {| E
* | DoublyLinkedListNode<E>
* | ((node: DoublyLinkedListNode<E>) => boolean)
* | undefined} elementNodeOrPredicate - The `getNode` method you provided is used to find a
* node in a doubly linked list based on a given element, node, or predicate function. The
* `elementNodeOrPredicate` parameter can be one of the following:
* @returns The `getNode` method returns a `DoublyLinkedListNode<E>` or `undefined` based on the
* input `elementNodeOrPredicate`. If the input is `undefined`, the method returns `undefined`.
* Otherwise, it iterates through the linked list starting from the head node and applies the
* provided predicate function to each node. If a node satisfies the predicate, that node is
* returned. If
* The function `findNodeByValue` searches for a node with a specific value in a doubly linked list and returns the
* node if found, otherwise it returns undefined.
* @param {E} value - The `value` parameter is the value that we want to search for in the doubly linked list.
* @returns The function `findNodeByValue` returns a `DoublyLinkedListNode<E>` if a node with the specified value `value`
* is found in the linked list. If no such node is found, it returns `undefined`.
*/
getNode(
elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean) | undefined
): DoublyLinkedListNode<E> | undefined {
if (elementNodeOrPredicate === undefined) return;
const predicate = this._ensurePredicate(elementNodeOrPredicate);
getNode(value: E | undefined): DoublyLinkedListNode<E> | undefined {
let current = this.head;
while (current) {
if (predicate(current)) {
if (current.value === value) {
return current;
}
current = current.next;
@ -768,28 +322,26 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* The `addAt` function inserts a new element or node at a specified index in a doubly linked list.
* @param {number} index - The `index` parameter in the `addAt` method represents the position at
* which you want to add a new element or node in the doubly linked list. It indicates the location
* where the new element or node should be inserted.
* @param {E | DoublyLinkedListNode<E>} newElementOrNode - The `newElementOrNode` parameter in the
* `addAt` method can be either a value of type `E` or a `DoublyLinkedListNode<E>` object.
* @returns The `addAt` method returns a boolean value. It returns `true` if the element or node was
* successfully added at the specified index, and `false` if the index is out of bounds (less than 0
* or greater than the size of the list).
* The `insert` function inserts a value at a specified index in a doubly linked list.
* @param {number} index - The index parameter represents the position at which the new value should be inserted in the
* DoublyLinkedList. It is of type number.
* @param {E} value - The `value` parameter represents the value that you want to insert into the Doubly Linked List at the
* specified index.
* @returns The `insert` method returns a boolean value. It returns `true` if the insertion is successful, and `false`
* if the index is out of bounds.
*/
addAt(index: number, newElementOrNode: E | DoublyLinkedListNode<E>): boolean {
addAt(index: number, value: E): boolean {
if (index < 0 || index > this._size) return false;
if (index === 0) {
this.unshift(newElementOrNode);
this.unshift(value);
return true;
}
if (index === this._size) {
this.push(newElementOrNode);
this.push(value);
return true;
}
const newNode = this._ensureNode(newElementOrNode);
const newNode = new DoublyLinkedListNode(value);
const prevNode = this.getNodeAt(index - 1);
const nextNode = prevNode!.next;
newNode.prev = prevNode;
@ -804,25 +356,26 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(1) or O(n)
* Space Complexity: O(1)
*
* The `addBefore` function in TypeScript adds a new element or node before an existing element or
* node in a doubly linked list.
* @param {E | DoublyLinkedListNode<E>} existingElementOrNode - The `existingElementOrNode` parameter
* in the `addBefore` method can be either an element of type `E` or a `DoublyLinkedListNode<E>`.
* @param {E | DoublyLinkedListNode<E>} newElementOrNode - The `newElementOrNode` parameter
* represents the element or node that you want to add before the `existingElementOrNode` in a doubly
* linked list.
* @returns The `addBefore` method returns a boolean value - `true` if the new element or node was
* successfully added before the existing element or node, and `false` if the existing element or
* node was not found.
* The `addBefore` function inserts a new value before an existing value or node in a doubly linked list.
* @param {E | DoublyLinkedListNode<E>} existingValueOrNode - The existing value or node in the doubly linked list
* before which the new value will be inserted. It can be either the value of the existing node or the existing node
* itself.
* @param {E} newValue - The `newValue` parameter represents the value that you want to insert into the doubly linked
* list.
* @returns The method returns a boolean value. It returns `true` if the insertion is successful, and `false` if the
* insertion fails.
*/
addBefore(
existingElementOrNode: E | DoublyLinkedListNode<E>,
newElementOrNode: E | DoublyLinkedListNode<E>
): boolean {
const existingNode: DoublyLinkedListNode<E> | undefined = this.getNode(existingElementOrNode);
addBefore(existingValueOrNode: E | DoublyLinkedListNode<E>, newValue: E): boolean {
let existingNode;
if (existingValueOrNode instanceof DoublyLinkedListNode) {
existingNode = existingValueOrNode;
} else {
existingNode = this.getNode(existingValueOrNode);
}
if (existingNode) {
const newNode = this._ensureNode(newElementOrNode);
const newNode = new DoublyLinkedListNode(newValue);
newNode.prev = existingNode.prev;
if (existingNode.prev) {
existingNode.prev.next = newNode;
@ -843,23 +396,25 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(1) or O(n)
* Space Complexity: O(1)
*
* The `addAfter` function in TypeScript adds a new element or node after an existing element or node
* in a doubly linked list.
* @param {E | DoublyLinkedListNode<E>} existingElementOrNode - existingElementOrNode represents the
* element or node in the doubly linked list after which you want to add a new element or node.
* @param {E | DoublyLinkedListNode<E>} newElementOrNode - The `newElementOrNode` parameter in the
* `addAfter` method represents the element or node that you want to add after the existing element
* or node in a doubly linked list. This parameter can be either an element value or a
* `DoublyLinkedListNode` object that you want to insert
* @returns The `addAfter` method returns a boolean value - `true` if the new element or node was
* successfully added after the existing element or node, and `false` if the existing element or node
* was not found in the linked list.
* The `addAfter` function inserts a new node with a given value after an existing node in a doubly linked list.
* @param {E | DoublyLinkedListNode<E>} existingValueOrNode - The existing value or node in the doubly linked list
* after which the new value will be inserted. It can be either the value of the existing node or the existing node
* itself.
* @param {E} newValue - The value that you want to insert into the doubly linked list.
* @returns The method returns a boolean value. It returns true if the insertion is successful, and false if the
* existing value or node is not found in the doubly linked list.
*/
addAfter(existingElementOrNode: E | DoublyLinkedListNode<E>, newElementOrNode: E | DoublyLinkedListNode<E>): boolean {
const existingNode: DoublyLinkedListNode<E> | undefined = this.getNode(existingElementOrNode);
addAfter(existingValueOrNode: E | DoublyLinkedListNode<E>, newValue: E): boolean {
let existingNode;
if (existingValueOrNode instanceof DoublyLinkedListNode) {
existingNode = existingValueOrNode;
} else {
existingNode = this.getNode(existingValueOrNode);
}
if (existingNode) {
const newNode = this._ensureNode(newElementOrNode);
const newNode = new DoublyLinkedListNode(newValue);
newNode.next = existingNode.next;
if (existingNode.next) {
existingNode.next.prev = newNode;
@ -910,17 +465,20 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(1) or O(n)
* Space Complexity: O(1)
*
* The `delete` function removes a specified element or node from a doubly linked list if it exists.
* @param {E | DoublyLinkedListNode<E> | undefined} elementOrNode - The `elementOrNode` parameter in
* the `delete` method can accept an element of type `E`, a `DoublyLinkedListNode` of type `E`, or it
* can be `undefined`. This parameter is used to identify the node that needs to be deleted from the
* doubly linked list
* @returns The `delete` method returns a boolean value - `true` if the element or node was
* successfully deleted from the doubly linked list, and `false` if the element or node was not found
* in the list.
* The `delete` function removes a node from a doubly linked list based on either the node itself or its value.
* @param {E | DoublyLinkedListNode<E>} valOrNode - The `valOrNode` parameter can accept either a value of type `E` or
* a `DoublyLinkedListNode<E>` object.
* @returns The `delete` method returns a boolean value. It returns `true` if the value or node was successfully
* deleted from the doubly linked list, and `false` if the value or node was not found in the list.
*/
delete(elementOrNode: E | DoublyLinkedListNode<E> | undefined): boolean {
const node: DoublyLinkedListNode<E> | undefined = this.getNode(elementOrNode);
delete(valOrNode: E | DoublyLinkedListNode<E> | undefined): boolean {
let node: DoublyLinkedListNode<E> | undefined;
if (valOrNode instanceof DoublyLinkedListNode) {
node = valOrNode;
} else {
node = this.getNode(valOrNode);
}
if (node) {
if (node === this.head) {
@ -930,8 +488,8 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
} else {
const prevNode = node.prev;
const nextNode = node.next;
if (prevNode) prevNode.next = nextNode;
if (nextNode) nextNode.prev = prevNode;
prevNode!.next = nextNode;
nextNode!.prev = prevNode;
this._size--;
}
return true;
@ -966,19 +524,17 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* This function finds the index of a specified element, node, or predicate in a doubly linked list.
* @param {E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)}
* elementNodeOrPredicate - The `indexOf` method takes in a parameter `elementNodeOrPredicate`, which
* can be one of the following:
* @returns The `indexOf` method returns the index of the element in the doubly linked list that
* matches the provided element, node, or predicate. If no match is found, it returns -1.
* The function returns the index of the first occurrence of a given value in a linked list.
* @param {E} value - The parameter `value` is of type `E`, which means it can be any data type. It represents the value
* that we are searching for in the linked list.
* @returns The method `indexOf` returns the index of the first occurrence of the specified value `value` in the linked
* list. If the value is not found, it returns -1.
*/
indexOf(elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)): number {
const predicate = this._ensurePredicate(elementNodeOrPredicate);
indexOf(value: E): number {
let index = 0;
let current = this.head;
while (current) {
if (predicate(current)) {
if (current.value === value) {
return index;
}
index++;
@ -991,46 +547,19 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* This function retrieves an element from a doubly linked list based on a given element
* node or predicate.
* @param {E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)} elementNodeOrPredicate
* elementNodeOrPredicate - The `get` method takes in a parameter called `elementNodeOrPredicate`,
* which can be one of the following types:
* @returns The `get` method returns the value of the first node in the doubly linked list that
* satisfies the provided predicate function. If no such node is found, it returns `undefined`.
* The `findBackward` function iterates through a linked list from the last node to the first node and returns the last
* value that satisfies the given callback function, or undefined if no value satisfies the callback.
* @param callback - A function that takes a value of type E as its parameter and returns a boolean value. This
* function is used to determine whether a given value satisfies a certain condition.
* @returns The method `findBackward` returns the last value in the linked list that satisfies the condition specified by
* the callback function. If no value satisfies the condition, it returns `undefined`.
*/
get(
elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)
): E | undefined {
const predicate = this._ensurePredicate(elementNodeOrPredicate);
let current = this.head;
while (current) {
if (predicate(current)) return current.value;
current = current.next;
}
return undefined;
}
/**
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* The `getBackward` function searches for a specific element in a doubly linked list starting from
* the tail and moving backwards.
* @param {E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)} elementNodeOrPredicate
* elementNodeOrPredicate - The `elementNodeOrPredicate` parameter in the `getBackward`
* function can be one of the following types:
* @returns The `getBackward` method returns the value of the element node that matches the provided
* predicate when traversing the doubly linked list backwards. If no matching element is found, it
* returns `undefined`.
*/
getBackward(
elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)
): E | undefined {
const predicate = this._ensurePredicate(elementNodeOrPredicate);
findBackward(callback: (value: E) => boolean): E | undefined {
let current = this.tail;
while (current) {
if (predicate(current)) return current.value;
if (callback(current.value)) {
return current.value;
}
current = current.prev;
}
return undefined;
@ -1164,39 +693,6 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
return mappedList;
}
/**
* Time Complexity: O(n)
* Space Complexity: O(1)
*
*/
countOccurrences(elementOrNode: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)): number {
const predicate = this._ensurePredicate(elementOrNode);
let count = 0;
let current = this.head;
while (current) {
if (predicate(current)) {
count++;
}
current = current.next;
}
return count;
}
/**
* Time Complexity: O(n)
* Space Complexity: O(n)
*
* The `fromArray` function creates a new instance of a DoublyLinkedList and populates it with the elements from the
* given array.
* @param {E[]} data - The `data` parameter is an array of elements of type `E`.
* @returns The `fromArray` function returns a DoublyLinkedList object.
*/
static fromArray<E>(data: E[]) {
return new DoublyLinkedList<E>(data);
}
/**
* The function returns an iterator that iterates over the values of a linked list.
*/
@ -1208,53 +704,4 @@ export class DoublyLinkedList<E = any, R = any> extends IterableElementBase<E, R
current = current.next;
}
}
/**
* The function `_isPredicate` checks if the input is a function that takes a `DoublyLinkedListNode`
* as an argument and returns a boolean.
* @param {E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)} elementNodeOrPredicate
* elementNodeOrPredicate - The `elementNodeOrPredicate` parameter can be one of the following
* types:
* @returns The _isPredicate method is returning a boolean value indicating whether the
* elementNodeOrPredicate parameter is a function or not. If the elementNodeOrPredicate is a
* function, the method will return true, indicating that it is a predicate function.
*/
protected _isPredicate(
elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)
): elementNodeOrPredicate is (node: DoublyLinkedListNode<E>) => boolean {
return typeof elementNodeOrPredicate === 'function';
}
/**
* The function `_ensureNode` ensures that the input is a valid node in a doubly linked list.
* @param {E | DoublyLinkedListNode<E>} elementOrNode - The `elementOrNode` parameter can be either
* an element of type `E` or a `DoublyLinkedListNode` containing an element of type `E`.
* @returns If the `elementOrNode` parameter is already a `DoublyLinkedListNode`, it will be returned
* as is. Otherwise, a new `DoublyLinkedListNode` instance will be created with the `elementOrNode`
* value and returned.
*/
protected _ensureNode(elementOrNode: E | DoublyLinkedListNode<E>) {
if (this.isNode(elementOrNode)) return elementOrNode;
return new DoublyLinkedListNode<E>(elementOrNode);
}
/**
* The function `_ensurePredicate` in TypeScript ensures that the input is either a node, a predicate
* function, or a value to compare with the node's value.
* @param {E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)} elementNodeOrPredicate
* elementNodeOrPredicate - The `elementNodeOrPredicate` parameter can be one of the following
* types:
* @returns A function is being returned that takes a `DoublyLinkedListNode` as a parameter and
* returns a boolean value based on the conditions specified in the code.
*/
protected _ensurePredicate(
elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)
) {
if (this.isNode(elementNodeOrPredicate)) return (node: DoublyLinkedListNode<E>) => node === elementNodeOrPredicate;
if (this._isPredicate(elementNodeOrPredicate)) return elementNodeOrPredicate;
return (node: DoublyLinkedListNode<E>) => node.value === elementNodeOrPredicate;
}
}

View file

@ -121,17 +121,34 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
return this._size;
}
/**
* Time Complexity: O(n)
* Space Complexity: O(n)
*
* The `fromArray` function creates a new SinglyLinkedList instance and populates it with the elements from the given
* array.
* @param {E[]} data - The `data` parameter is an array of elements of type `E`.
* @returns The `fromArray` function returns a `SinglyLinkedList` object.
*/
static fromArray<E>(data: E[]) {
const singlyLinkedList = new SinglyLinkedList<E>();
for (const item of data) {
singlyLinkedList.push(item);
}
return singlyLinkedList;
}
/**
* Time Complexity: O(1)
* Space Complexity: O(1)
*
* The `push` function adds a new element or node to the end of a singly linked list.
* @param {E | SinglyLinkedListNode<E>} elementOrNode - The `elementOrNode` parameter in the `push`
* method can accept either an element of type `E` or a `SinglyLinkedListNode<E>` object.
* @returns The `push` method is returning a boolean value, specifically `true`.
* The push function adds a new element to the end of a singly linked list.
* @param {E} element - The "element" parameter represents the value of the element that you want to
* add to the linked list.
* @returns The `push` method is returning a boolean value, `true`.
*/
push(elementOrNode: E | SinglyLinkedListNode<E>): boolean {
const newNode = this._ensureNode(elementOrNode);
push(element: E): boolean {
const newNode = new SinglyLinkedListNode(element);
if (!this.head) {
this._head = newNode;
this._tail = newNode;
@ -191,15 +208,13 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(1)
* Space Complexity: O(1)
*
* The unshift function adds a new element or node to the beginning of a singly linked list in
* TypeScript.
* @param {E | SinglyLinkedListNode<E>} elementOrNode - The `elementOrNode` parameter in the
* `unshift` method can be either an element of type `E` or a `SinglyLinkedListNode` containing an
* element of type `E`.
* @returns The `unshift` method is returning a boolean value, specifically `true`.
* The unshift function adds a new element to the beginning of a singly linked list.
* @param {E} element - The "element" parameter represents the value of the element that you want to
* add to the beginning of the singly linked list.
* @returns The `unshift` method is returning a boolean value, `true`.
*/
unshift(elementOrNode: E | SinglyLinkedListNode<E>): boolean {
const newNode = this._ensureNode(elementOrNode);
unshift(element: E): boolean {
const newNode = new SinglyLinkedListNode(element);
if (!this.head) {
this._head = newNode;
this._tail = newNode;
@ -211,30 +226,6 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
return true;
}
/**
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* This function searches for a specific element in a singly linked list based on a given node or
* predicate.
* @param {E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)} elementNodeOrPredicate
* elementNodeOrPredicate - The `elementNodeOrPredicate` parameter in the `get` method can be one of
* the following types:
* @returns The `get` method returns the value of the first node in the singly linked list that
* satisfies the provided predicate function. If no such node is found, it returns `undefined`.
*/
get(
elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)
): E | undefined {
const predicate = this._ensurePredicate(elementNodeOrPredicate);
let current = this.head;
while (current) {
if (predicate(current)) return current.value;
current = current.next;
}
return undefined;
}
/**
* Time Complexity: O(n)
* Space Complexity: O(1)
@ -254,25 +245,6 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
return current!.value;
}
/**
* Time Complexity: O(1)
* Space Complexity: O(1)
*
* The function `isNode` in TypeScript checks if the input is an instance of `SinglyLinkedListNode`.
* @param {E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)} elementNodeOrPredicate
* elementNodeOrPredicate - The `elementNodeOrPredicate` parameter in the `isNode` function can be
* one of the following types:
* @returns The `isNode` function is checking if the `elementNodeOrPredicate` parameter is an
* instance of `SinglyLinkedListNode<E>`. If it is, the function returns `true`, indicating that the
* parameter is a `SinglyLinkedListNode<E>`. If it is not an instance of `SinglyLinkedListNode<E>`,
* the function returns `false`.
*/
isNode(
elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)
): elementNodeOrPredicate is SinglyLinkedListNode<E> {
return elementNodeOrPredicate instanceof SinglyLinkedListNode;
}
/**
* Time Complexity: O(n)
* Space Complexity: O(1)
@ -324,18 +296,18 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Space Complexity: O(1)
*
* The delete function removes a node with a specific value from a singly linked list.
* @param {E | SinglyLinkedListNode<E>} elementOrNode - The `elementOrNode` parameter can accept either a value of type `E`
* @param {E | SinglyLinkedListNode<E>} valueOrNode - The `valueOrNode` parameter can accept either a value of type `E`
* or a `SinglyLinkedListNode<E>` object.
* @returns The `delete` method returns a boolean value. It returns `true` if the value or node is found and
* successfully deleted from the linked list, and `false` if the value or node is not found in the linked list.
*/
delete(elementOrNode: E | SinglyLinkedListNode<E> | undefined): boolean {
if (elementOrNode === undefined) return false;
delete(valueOrNode: E | SinglyLinkedListNode<E> | undefined): boolean {
if (valueOrNode === undefined) return false;
let value: E;
if (elementOrNode instanceof SinglyLinkedListNode) {
value = elementOrNode.value;
if (valueOrNode instanceof SinglyLinkedListNode) {
value = valueOrNode.value;
} else {
value = elementOrNode;
value = valueOrNode;
}
let current = this.head,
prev = undefined;
@ -367,30 +339,26 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* The `addAt` function inserts a new element or node at a specified index in a singly linked list.
* @param {number} index - The `index` parameter represents the position at which you want to add a
* new element or node in the linked list. It is a number that indicates the index where the new
* element or node should be inserted.
* @param {E | SinglyLinkedListNode<E>} newElementOrNode - The `newElementOrNode` parameter in the
* `addAt` method can be either a value of type `E` or a `SinglyLinkedListNode<E>` object. This
* parameter represents the element or node that you want to add to the linked list at the specified
* index.
* @returns The `addAt` method returns a boolean value - `true` if the element or node was
* successfully added at the specified index, and `false` if the index is out of bounds.
* The `addAt` function inserts a value at a specified index in a singly linked list.
* @param {number} index - The index parameter represents the position at which the new value should be inserted in the
* linked list. It is of type number.
* @param {E} value - The `value` parameter represents the value that you want to insert into the linked list at the
* specified index.
* @returns The `insert` method returns a boolean value. It returns `true` if the insertion is successful, and `false`
* if the index is out of bounds.
*/
addAt(index: number, newElementOrNode: E | SinglyLinkedListNode<E>): boolean {
addAt(index: number, value: E): boolean {
if (index < 0 || index > this._size) return false;
if (index === 0) {
this.unshift(newElementOrNode);
this.unshift(value);
return true;
}
if (index === this._size) {
this.push(newElementOrNode);
this.push(value);
return true;
}
const newNode = this._ensureNode(newElementOrNode);
const newNode = new SinglyLinkedListNode(value);
const prevNode = this.getNodeAt(index - 1);
newNode.next = prevNode!.next;
prevNode!.next = newNode;
@ -462,22 +430,17 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* The `indexOf` function in TypeScript searches for a specific element or node in a singly linked
* list and returns its index if found.
* @param {E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)} elementNodeOrPredicate
* elementNodeOrPredicate - The `elementNodeOrPredicate` parameter in the `indexOf` method can be one
* of the following types:
* @returns The `indexOf` method returns the index of the first occurrence of the element that
* matches the provided predicate in the singly linked list. If no matching element is found, it
* returns -1.
* The `indexOf` function returns the index of the first occurrence of a given value in a linked list.
* @param {E} value - The value parameter is the value that you want to find the index of in the linked list.
* @returns The method is returning the index of the first occurrence of the specified value in the linked list. If the
* value is not found, it returns -1.
*/
indexOf(elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)): number {
const predicate = this._ensurePredicate(elementNodeOrPredicate);
indexOf(value: E): number {
let index = 0;
let current = this.head;
while (current) {
if (predicate(current)) {
if (current.value === value) {
return index;
}
index++;
@ -491,24 +454,17 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* The function `getNode` in TypeScript searches for a node in a singly linked list based on a given
* element, node, or predicate.
* @param {E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean) | undefined} elementNodeOrPredicate
* elementNodeOrPredicate - The `elementNodeOrPredicate` parameter in the `getNode` method can be one
* of the following types:
* @returns The `getNode` method returns either a `SinglyLinkedListNode<E>` if a matching node is
* found based on the provided predicate, or it returns `undefined` if no matching node is found or
* if the input parameter is `undefined`.
* The function finds a node in a singly linked list by its value and returns the node if found, otherwise returns
* undefined.
* @param {E} value - The value parameter is the value that we want to search for in the linked list.
* @returns a `SinglyLinkedListNode<E>` if a node with the specified value is found in the linked list. If no node with
* the specified value is found, the function returns `undefined`.
*/
getNode(
elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean) | undefined
): SinglyLinkedListNode<E> | undefined {
if (elementNodeOrPredicate === undefined) return;
const predicate = this._ensurePredicate(elementNodeOrPredicate);
getNode(value: E): SinglyLinkedListNode<E> | undefined {
let current = this.head;
while (current) {
if (predicate(current)) {
if (current.value === value) {
return current;
}
current = current.next;
@ -521,39 +477,31 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* The function `addBefore` in TypeScript adds a new element or node before an existing element or
* node in a singly linked list.
* @param {E | SinglyLinkedListNode<E>} existingElementOrNode - existingElementOrNode represents the
* element or node in the linked list before which you want to add a new element or node.
* @param {E | SinglyLinkedListNode<E>} newElementOrNode - The `newElementOrNode` parameter in the
* `addBefore` method represents the element or node that you want to insert before the existing
* element or node in the linked list. This new element can be of type `E` or a
* `SinglyLinkedListNode<E>`.
* @returns The `addBefore` method returns a boolean value - `true` if the new element or node was
* successfully added before the existing element or node, and `false` if the operation was
* unsuccessful.
* The `addBefore` function inserts a new value before an existing value in a singly linked list.
* @param {E | SinglyLinkedListNode<E>} existingValueOrNode - The existing value or node that you want to insert the
* new value before. It can be either the value itself or a node containing the value in the linked list.
* @param {E} newValue - The `newValue` parameter represents the value that you want to insert into the linked list.
* @returns The method `addBefore` returns a boolean value. It returns `true` if the new value was successfully
* inserted before the existing value, and `false` otherwise.
*/
addBefore(
existingElementOrNode: E | SinglyLinkedListNode<E>,
newElementOrNode: E | SinglyLinkedListNode<E>
): boolean {
addBefore(existingValueOrNode: E | SinglyLinkedListNode<E>, newValue: E): boolean {
if (!this.head) return false;
let existingValue: E;
if (this.isNode(existingElementOrNode)) {
existingValue = existingElementOrNode.value;
if (existingValueOrNode instanceof SinglyLinkedListNode) {
existingValue = existingValueOrNode.value;
} else {
existingValue = existingElementOrNode;
existingValue = existingValueOrNode;
}
if (this.head.value === existingValue) {
this.unshift(newElementOrNode);
this.unshift(newValue);
return true;
}
let current = this.head;
while (current.next) {
if (current.next.value === existingValue) {
const newNode = this._ensureNode(newElementOrNode);
const newNode = new SinglyLinkedListNode(newValue);
newNode.next = current.next;
current.next = newNode;
this._size++;
@ -569,23 +517,24 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* The `addAfter` function in TypeScript adds a new element or node after an existing element or node
* in a singly linked list.
* @param {E | SinglyLinkedListNode<E>} existingElementOrNode - existingElementOrNode can be either
* an element of type E or a SinglyLinkedListNode of type E.
* @param {E | SinglyLinkedListNode<E>} newElementOrNode - The `newElementOrNode` parameter in the
* `addAfter` method represents the element or node that you want to add after the existing element
* or node in a singly linked list. This parameter can be either the value of the new element or a
* reference to a `SinglyLinkedListNode` containing
* @returns The `addAfter` method returns a boolean value - `true` if the new element or node was
* successfully added after the existing element or node, and `false` if the existing element or node
* was not found.
* The `addAfter` function inserts a new node with a given value after an existing node in a singly linked list.
* @param {E | SinglyLinkedListNode<E>} existingValueOrNode - The existing value or node in the linked list after which
* the new value will be inserted. It can be either the value of the existing node or the existing node itself.
* @param {E} newValue - The value that you want to insert into the linked list after the existing value or node.
* @returns The method returns a boolean value. It returns true if the new value was successfully inserted after the
* existing value or node, and false if the existing value or node was not found in the linked list.
*/
addAfter(existingElementOrNode: E | SinglyLinkedListNode<E>, newElementOrNode: E | SinglyLinkedListNode<E>): boolean {
const existingNode: SinglyLinkedListNode<E> | undefined = this.getNode(existingElementOrNode);
addAfter(existingValueOrNode: E | SinglyLinkedListNode<E>, newValue: E): boolean {
let existingNode: E | SinglyLinkedListNode<E> | undefined;
if (existingValueOrNode instanceof SinglyLinkedListNode) {
existingNode = existingValueOrNode;
} else {
existingNode = this.getNode(existingValueOrNode);
}
if (existingNode) {
const newNode = this._ensureNode(newElementOrNode);
const newNode = new SinglyLinkedListNode(newValue);
newNode.next = existingNode.next;
existingNode.next = newNode;
if (existingNode === this.tail) {
@ -602,20 +551,16 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* The function `countOccurrences` iterates through a singly linked list and counts the occurrences
* of a specified element or nodes that satisfy a given predicate.
* @param {E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)} elementOrNode
* - The `elementOrNode` parameter in the `countOccurrences` method can accept three types of values:
* @returns The `countOccurrences` method returns the number of occurrences of the specified element,
* node, or predicate function in the singly linked list.
* The function counts the number of occurrences of a given value in a linked list.
* @param {E} value - The value parameter is the value that you want to count the occurrences of in the linked list.
* @returns The count of occurrences of the given value in the linked list.
*/
countOccurrences(elementOrNode: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)): number {
const predicate = this._ensurePredicate(elementOrNode);
countOccurrences(value: E): number {
let count = 0;
let current = this.head;
while (current) {
if (predicate(current)) {
if (current.value === value) {
count++;
}
current = current.next;
@ -712,70 +657,4 @@ export class SinglyLinkedList<E = any, R = any> extends IterableElementBase<E, R
current = current.next;
}
}
/**
* Time Complexity: O(n)
* Space Complexity: O(n)
*
* The `fromArray` function creates a new SinglyLinkedList instance and populates it with the elements from the given
* array.
* @param {E[]} data - The `data` parameter is an array of elements of type `E`.
* @returns The `fromArray` function returns a `SinglyLinkedList` object.
*/
static fromArray<E>(data: E[]) {
const singlyLinkedList = new SinglyLinkedList<E>();
for (const item of data) {
singlyLinkedList.push(item);
}
return singlyLinkedList;
}
/**
* The _isPredicate function in TypeScript checks if the input is a function that takes a
* SinglyLinkedListNode as an argument and returns a boolean.
* @param {E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)} elementNodeOrPredicate
* elementNodeOrPredicate - The `elementNodeOrPredicate` parameter can be one of the following types:
* @returns The _isPredicate method is returning a boolean value based on whether the
* elementNodeOrPredicate parameter is a function or not. If the elementNodeOrPredicate is a
* function, the method will return true, indicating that it is a predicate function. If it is not a
* function, the method will return false.
*/
protected _isPredicate(
elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)
): elementNodeOrPredicate is (node: SinglyLinkedListNode<E>) => boolean {
return typeof elementNodeOrPredicate === 'function';
}
/**
* The function `_ensureNode` ensures that the input is a valid node and returns it, creating a new
* node if necessary.
* @param {E | SinglyLinkedListNode<E>} elementOrNode - The `elementOrNode` parameter can be either
* an element of type `E` or a `SinglyLinkedListNode` containing an element of type `E`.
* @returns A SinglyLinkedListNode<E> object is being returned.
*/
protected _ensureNode(elementOrNode: E | SinglyLinkedListNode<E>) {
if (this.isNode(elementOrNode)) return elementOrNode;
return new SinglyLinkedListNode<E>(elementOrNode);
}
/**
* The function `_ensurePredicate` in TypeScript ensures that the input is either a node, a predicate
* function, or a value to compare with the node's value.
* @param {E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)} elementNodeOrPredicate
* elementNodeOrPredicate - The `elementNodeOrPredicate` parameter can be one of the following types:
* @returns A function is being returned. If the input `elementNodeOrPredicate` is already a node, a
* function is returned that checks if a given node is equal to the input node. If the input is a
* predicate function, it is returned as is. If the input is neither a node nor a predicate function,
* a function is returned that checks if a given node's value is equal to the input
*/
protected _ensurePredicate(
elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)
) {
if (this.isNode(elementNodeOrPredicate)) return (node: SinglyLinkedListNode<E>) => node === elementNodeOrPredicate;
if (this._isPredicate(elementNodeOrPredicate)) return elementNodeOrPredicate;
return (node: SinglyLinkedListNode<E>) => node.value === elementNodeOrPredicate;
}
}

View file

@ -457,176 +457,3 @@ describe('FibonacciHeap Stress Test', () => {
);
});
});
describe('classic use', () => {
it('@example Use Heap to sort an array', () => {
function heapSort(arr: number[]): number[] {
const heap = new Heap<number>(arr, { comparator: (a, b) => a - b });
const sorted: number[] = [];
while (!heap.isEmpty()) {
sorted.push(heap.poll()!); // Poll minimum element
}
return sorted;
}
const array = [5, 3, 8, 4, 1, 2];
expect(heapSort(array)).toEqual([1, 2, 3, 4, 5, 8]);
});
it('@example Use Heap to solve top k problems', () => {
function topKElements(arr: number[], k: number): number[] {
const heap = new Heap<number>([], { comparator: (a, b) => b - a }); // Max heap
arr.forEach(num => {
heap.add(num);
if (heap.size > k) heap.poll(); // Keep the heap size at K
});
return heap.toArray();
}
const numbers = [10, 30, 20, 5, 15, 25];
expect(topKElements(numbers, 3)).toEqual([15, 10, 5]);
});
it('@example Use Heap to merge sorted sequences', () => {
function mergeSortedSequences(sequences: number[][]): number[] {
const heap = new Heap<{ value: number; seqIndex: number; itemIndex: number }>([], {
comparator: (a, b) => a.value - b.value // Min heap
});
// Initialize heap
sequences.forEach((seq, seqIndex) => {
if (seq.length) {
heap.add({ value: seq[0], seqIndex, itemIndex: 0 });
}
});
const merged: number[] = [];
while (!heap.isEmpty()) {
const { value, seqIndex, itemIndex } = heap.poll()!;
merged.push(value);
if (itemIndex + 1 < sequences[seqIndex].length) {
heap.add({
value: sequences[seqIndex][itemIndex + 1],
seqIndex,
itemIndex: itemIndex + 1
});
}
}
return merged;
}
const sequences = [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
];
expect(mergeSortedSequences(sequences)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);
});
it('@example Use Heap to dynamically maintain the median', () => {
class MedianFinder {
private low: MaxHeap<number>; // Max heap, stores the smaller half
private high: MinHeap<number>; // Min heap, stores the larger half
constructor() {
this.low = new MaxHeap<number>([]);
this.high = new MinHeap<number>([]);
}
addNum(num: number): void {
if (this.low.isEmpty() || num <= this.low.peek()!) this.low.add(num);
else this.high.add(num);
// Balance heaps
if (this.low.size > this.high.size + 1) this.high.add(this.low.poll()!);
else if (this.high.size > this.low.size) this.low.add(this.high.poll()!);
}
findMedian(): number {
if (this.low.size === this.high.size) return (this.low.peek()! + this.high.peek()!) / 2;
return this.low.peek()!;
}
}
const medianFinder = new MedianFinder();
medianFinder.addNum(10);
expect(medianFinder.findMedian()).toBe(10);
medianFinder.addNum(20);
expect(medianFinder.findMedian()).toBe(15);
medianFinder.addNum(30);
expect(medianFinder.findMedian()).toBe(20);
medianFinder.addNum(40);
expect(medianFinder.findMedian()).toBe(25);
medianFinder.addNum(50);
expect(medianFinder.findMedian()).toBe(30);
});
it('@example Use Heap for load balancing', () => {
function loadBalance(requests: number[], servers: number): number[] {
const serverHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // min heap
const serverLoads = new Array(servers).fill(0);
for (let i = 0; i < servers; i++) {
serverHeap.add({ id: i, load: 0 });
}
requests.forEach(req => {
const server = serverHeap.poll()!;
serverLoads[server.id] += req;
server.load += req;
serverHeap.add(server); // The server after updating the load is re-entered into the heap
});
return serverLoads;
}
const requests = [5, 2, 8, 3, 7];
expect(loadBalance(requests, 3)).toEqual([12, 8, 5]);
});
it('@example Use Heap to schedule tasks', () => {
type Task = [string, number];
function scheduleTasks(tasks: Task[], machines: number): Map<number, Task[]> {
const machineHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // Min heap
const allocation = new Map<number, Task[]>();
// Initialize the load on each machine
for (let i = 0; i < machines; i++) {
machineHeap.add({ id: i, load: 0 });
allocation.set(i, []);
}
// Assign tasks
tasks.forEach(([task, load]) => {
const machine = machineHeap.poll()!;
allocation.get(machine.id)!.push([task, load]);
machine.load += load;
machineHeap.add(machine); // The machine after updating the load is re-entered into the heap
});
return allocation;
}
const tasks: Task[] = [
['Task1', 3],
['Task2', 1],
['Task3', 2],
['Task4', 5],
['Task5', 4]
];
const expectedMap = new Map<number, Task[]>();
expectedMap.set(0, [
['Task1', 3],
['Task4', 5]
]);
expectedMap.set(1, [
['Task2', 1],
['Task3', 2],
['Task5', 4]
]);
expect(scheduleTasks(tasks, 2)).toEqual(expectedMap);
});
});

View file

@ -78,8 +78,8 @@ describe('DoublyLinkedList Operation Test', () => {
expect(list.indexOf(6)).toBe(-1);
});
it('should getBackward undefined', () => {
expect(list.getBackward(node => node.value === 0)).toBe(undefined);
it('should findBackward undefined', () => {
expect(list.findBackward(value => value === 0)).toBe(undefined);
});
it('should addAfter tail', () => {
@ -295,7 +295,7 @@ describe('DoublyLinkedList Operation Test', () => {
list.push(3);
list.push(4);
const lastEven = list.getBackward(node => node.value % 2 === 0);
const lastEven = list.findBackward(value => value % 2 === 0);
expect(lastEven).toBe(4);
});
@ -502,437 +502,3 @@ describe('iterable methods', () => {
expect(dl.some(value => value > 100)).toBe(false);
});
});
describe('classic use', () => {
it('@example text editor operation history', () => {
const actions = [
{ type: 'insert', content: 'first line of text' },
{ type: 'insert', content: 'second line of text' },
{ type: 'delete', content: 'delete the first line' }
];
const editorHistory = new DoublyLinkedList<{ type: string; content: string }>(actions);
expect(editorHistory.last?.type).toBe('delete');
expect(editorHistory.pop()?.content).toBe('delete the first line');
expect(editorHistory.last?.type).toBe('insert');
});
it('@example Browser history', () => {
const browserHistory = new DoublyLinkedList<string>();
browserHistory.push('home page');
browserHistory.push('search page');
browserHistory.push('details page');
expect(browserHistory.last).toBe('details page');
expect(browserHistory.pop()).toBe('details page');
expect(browserHistory.last).toBe('search page');
});
it('@example Use DoublyLinkedList to implement music player', () => {
// Define the Song interface
interface Song {
title: string;
artist: string;
duration: number; // duration in seconds
}
class Player {
private playlist: DoublyLinkedList<Song>;
private currentSong: ReturnType<typeof this.playlist.getNodeAt> | undefined;
constructor(songs: Song[]) {
this.playlist = new DoublyLinkedList<Song>();
songs.forEach(song => this.playlist.push(song));
this.currentSong = this.playlist.head;
}
// Play the next song in the playlist
playNext(): Song | undefined {
if (!this.currentSong?.next) {
this.currentSong = this.playlist.head; // Loop to the first song
} else {
this.currentSong = this.currentSong.next;
}
return this.currentSong?.value;
}
// Play the previous song in the playlist
playPrevious(): Song | undefined {
if (!this.currentSong?.prev) {
this.currentSong = this.playlist.tail; // Loop to the last song
} else {
this.currentSong = this.currentSong.prev;
}
return this.currentSong?.value;
}
// Get the current song
getCurrentSong(): Song | undefined {
return this.currentSong?.value;
}
// Loop through the playlist twice
loopThroughPlaylist(): Song[] {
const playedSongs: Song[] = [];
const initialNode = this.currentSong;
// Loop through the playlist twice
for (let i = 0; i < this.playlist.size * 2; i++) {
playedSongs.push(this.currentSong!.value);
this.currentSong = this.currentSong!.next || this.playlist.head; // Loop back to the start if needed
}
// Reset the current song to the initial song
this.currentSong = initialNode;
return playedSongs;
}
}
const songs = [
{ title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
{ title: 'Hotel California', artist: 'Eagles', duration: 391 },
{ title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
{ title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
];
let player = new Player(songs);
// should play the next song
player = new Player(songs);
const firstSong = player.getCurrentSong();
const nextSong = player.playNext();
// Expect the next song to be "Hotel California by Eagles"
expect(nextSong).toEqual({ title: 'Hotel California', artist: 'Eagles', duration: 391 });
expect(firstSong).toEqual({ title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 });
// should play the previous song
player = new Player(songs);
player.playNext(); // Move to the second song
const currentSong = player.getCurrentSong();
const previousSong = player.playPrevious();
// Expect the previous song to be "Bohemian Rhapsody by Queen"
expect(previousSong).toEqual({ title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 });
expect(currentSong).toEqual({ title: 'Hotel California', artist: 'Eagles', duration: 391 });
// should loop to the first song when playing next from the last song
player = new Player(songs);
player.playNext(); // Move to the second song
player.playNext(); // Move to the third song
player.playNext(); // Move to the fourth song
const nextSongToFirst = player.playNext(); // Should loop to the first song
// Expect the next song to be "Bohemian Rhapsody by Queen"
expect(nextSongToFirst).toEqual({ title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 });
// should loop to the last song when playing previous from the first song
player = new Player(songs);
player.playNext(); // Move to the first song
player.playNext(); // Move to the second song
player.playNext(); // Move to the third song
player.playNext(); // Move to the fourth song
const previousToLast = player.playPrevious(); // Should loop to the last song
// Expect the previous song to be "Billie Jean by Michael Jackson"
expect(previousToLast).toEqual({ title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 });
// should loop through the entire playlist
player = new Player(songs);
const playedSongs = player.loopThroughPlaylist();
// The expected order of songs for two loops
expect(playedSongs).toEqual([
{ title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
{ title: 'Hotel California', artist: 'Eagles', duration: 391 },
{ title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
{ title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 },
{ title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
{ title: 'Hotel California', artist: 'Eagles', duration: 391 },
{ title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
{ title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
]);
});
it('@example Use DoublyLinkedList to implement LRU cache', () => {
interface CacheEntry<K, V> {
key: K;
value: V;
}
class LRUCache<K = string, V = any> {
private readonly capacity: number;
private list: DoublyLinkedList<CacheEntry<K, V>>;
private map: Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>;
constructor(capacity: number) {
if (capacity <= 0) {
throw new Error('lru cache capacity must be greater than 0');
}
this.capacity = capacity;
this.list = new DoublyLinkedList<CacheEntry<K, V>>();
this.map = new Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>();
}
// Get cached value
get(key: K): V | undefined {
const node = this.map.get(key);
if (!node) return undefined;
// Move the visited node to the head of the linked list (most recently used)
this.moveToFront(node);
return node.value.value;
}
// Set cache value
set(key: K, value: V): void {
// Check if it already exists
const node = this.map.get(key);
if (node) {
// Update value and move to head
node.value.value = value;
this.moveToFront(node);
return;
}
// Check capacity
if (this.list.size >= this.capacity) {
// Delete the least recently used element (the tail of the linked list)
const removedNode = this.list.tail;
if (removedNode) {
this.map.delete(removedNode.value.key);
this.list.pop();
}
}
// Create new node and add to head
const newEntry: CacheEntry<K, V> = { key, value };
this.list.unshift(newEntry);
// Save node reference in map
const newNode = this.list.head;
if (newNode) {
this.map.set(key, newNode);
}
}
// Move the node to the head of the linked list
private moveToFront(node: DoublyLinkedListNode<CacheEntry<K, V>>): void {
this.list.delete(node);
this.list.unshift(node.value);
}
// Delete specific key
delete(key: K): boolean {
const node = this.map.get(key);
if (!node) return false;
// Remove from linked list
this.list.delete(node);
// Remove from map
this.map.delete(key);
return true;
}
// Clear cache
clear(): void {
this.list.clear();
this.map.clear();
}
// Get the current cache size
get size(): number {
return this.list.size;
}
// Check if it is empty
get isEmpty(): boolean {
return this.list.isEmpty();
}
}
// should set and get values correctly
const cache = new LRUCache<string, number>(3);
cache.set('a', 1);
cache.set('b', 2);
cache.set('c', 3);
expect(cache.get('a')).toBe(1);
expect(cache.get('b')).toBe(2);
expect(cache.get('c')).toBe(3);
// The least recently used element should be evicted when capacity is exceeded
cache.clear();
cache.set('a', 1);
cache.set('b', 2);
cache.set('c', 3);
cache.set('d', 4); // This will eliminate 'a'
expect(cache.get('a')).toBeUndefined();
expect(cache.get('b')).toBe(2);
expect(cache.get('c')).toBe(3);
expect(cache.get('d')).toBe(4);
// The priority of an element should be updated when it is accessed
cache.clear();
cache.set('a', 1);
cache.set('b', 2);
cache.set('c', 3);
cache.get('a'); // access 'a'
cache.set('d', 4); // This will eliminate 'b'
expect(cache.get('a')).toBe(1);
expect(cache.get('b')).toBeUndefined();
expect(cache.get('c')).toBe(3);
expect(cache.get('d')).toBe(4);
// Should support updating existing keys
cache.clear();
cache.set('a', 1);
cache.set('a', 10);
expect(cache.get('a')).toBe(10);
// Should support deleting specified keys
cache.clear();
cache.set('a', 1);
cache.set('b', 2);
expect(cache.delete('a')).toBe(true);
expect(cache.get('a')).toBeUndefined();
expect(cache.size).toBe(1);
// Should support clearing cache
cache.clear();
cache.set('a', 1);
cache.set('b', 2);
cache.clear();
expect(cache.size).toBe(0);
expect(cache.isEmpty).toBe(true);
});
it('@example finding lyrics by timestamp in Coldplay\'s "Fix You"', () => {
// Create a DoublyLinkedList to store song lyrics with timestamps
const lyricsList = new DoublyLinkedList<{ time: number; text: string }>();
// Detailed lyrics with precise timestamps (in milliseconds)
const lyrics = [
{ time: 0, text: "When you try your best, but you don't succeed" },
{ time: 4000, text: 'When you get what you want, but not what you need' },
{ time: 8000, text: "When you feel so tired, but you can't sleep" },
{ time: 12000, text: 'Stuck in reverse' },
{ time: 16000, text: 'And the tears come streaming down your face' },
{ time: 20000, text: "When you lose something you can't replace" },
{ time: 24000, text: 'When you love someone, but it goes to waste' },
{ time: 28000, text: 'Could it be worse?' },
{ time: 32000, text: 'Lights will guide you home' },
{ time: 36000, text: 'And ignite your bones' },
{ time: 40000, text: 'And I will try to fix you' }
];
// Populate the DoublyLinkedList with lyrics
lyrics.forEach(lyric => lyricsList.push(lyric));
// Test different scenarios of lyric synchronization
// 1. Find lyric at exact timestamp
const exactTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 36000);
expect(exactTimeLyric?.text).toBe('And ignite your bones');
// 2. Find lyric between timestamps
const betweenTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 22000);
expect(betweenTimeLyric?.text).toBe("When you lose something you can't replace");
// 3. Find first lyric when timestamp is less than first entry
const earlyTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= -1000);
expect(earlyTimeLyric).toBeUndefined();
// 4. Find last lyric when timestamp is after last entry
const lateTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 50000);
expect(lateTimeLyric?.text).toBe('And I will try to fix you');
});
it('@example cpu process schedules', () => {
class Process {
constructor(
public id: number,
public priority: number
) {}
execute(): string {
return `Process ${this.id} executed.`;
}
}
class Scheduler {
private queue: DoublyLinkedList<Process>;
constructor() {
this.queue = new DoublyLinkedList<Process>();
}
addProcess(process: Process): void {
// Insert processes into a queue based on priority, keeping priority in descending order
let current = this.queue.head;
while (current && current.value.priority >= process.priority) {
current = current.next;
}
if (!current) {
this.queue.push(process);
} else {
this.queue.addBefore(current, process);
}
}
executeNext(): string | undefined {
// Execute tasks at the head of the queue in order
const process = this.queue.shift();
return process ? process.execute() : undefined;
}
listProcesses(): string[] {
return this.queue.toArray().map(process => `Process ${process.id} (Priority: ${process.priority})`);
}
clear(): void {
this.queue.clear();
}
}
// should add processes based on priority
let scheduler = new Scheduler();
scheduler.addProcess(new Process(1, 10));
scheduler.addProcess(new Process(2, 20));
scheduler.addProcess(new Process(3, 15));
expect(scheduler.listProcesses()).toEqual([
'Process 2 (Priority: 20)',
'Process 3 (Priority: 15)',
'Process 1 (Priority: 10)'
]);
// should execute the highest priority process
scheduler = new Scheduler();
scheduler.addProcess(new Process(1, 10));
scheduler.addProcess(new Process(2, 20));
expect(scheduler.executeNext()).toBe('Process 2 executed.');
expect(scheduler.listProcesses()).toEqual(['Process 1 (Priority: 10)']);
// should clear all processes
scheduler = new Scheduler();
scheduler.addProcess(new Process(1, 10));
scheduler.addProcess(new Process(2, 20));
scheduler.clear();
expect(scheduler.listProcesses()).toEqual([]);
});
});

View file

@ -1,49 +1 @@
/**
* Convert any string to CamelCase format
*/
export function toCamelCase(str: string): string {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (_, chr) => chr.toUpperCase());
}
/**
* Convert any string to SnakeCase format
*/
export function toSnakeCase(str: string): string {
return str
.replace(/([a-z])([A-Z])/g, '$1_$2') // Add underline between lowercase and uppercase letters
.toLowerCase() // Convert to lowercase
.replace(/[^a-z0-9]+/g, '_'); // Replace non-alphanumeric characters with underscores
}
/**
* Convert any string to PascalCase format (first letter capitalized)
*/
export function toPascalCase(str: string): string {
return str
.replace(/([a-z])([A-Z])/g, '$1 $2') // Add space between lowercase and uppercase letters
.replace(/[^a-zA-Z0-9]+/g, ' ') // Replace non-alphanumeric characters with spaces
.split(' ') // Separate strings by spaces
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) // The first letter is capitalized, the rest are lowercase
.join(''); // Combine into a string
}
/**
* Convert CamelCase or SnakeCase string to string format with specified separator
*/
export function toSeparatedCase(str: string, separator: string = '_'): string {
return str
.replace(/([a-z0-9])([A-Z])/g, '$1' + separator + '$2')
.replace(/[_\s]+/g, separator)
.toLowerCase();
}
/**
* Convert the string to all uppercase and delimit it using the specified delimiter
*/
export function toUpperSeparatedCase(str: string, separator: string = '_'): string {
return str
.toUpperCase() // Convert all letters to uppercase
.replace(/([a-z0-9])([A-Z])/g, '$1' + separator + '$2') // Add separator between lowercase letters and uppercase letters
.replace(/[^A-Z0-9]+/g, separator) // Replace non-alphanumeric characters with separators
.replace(new RegExp(`^${separator}|${separator}$`, 'g'), ''); // Remove the starting and ending separators
}
export {};

View file

@ -1,215 +0,0 @@
import fs from 'fs';
import path from 'path';
import * as ts from 'typescript';
import { toPascalCase } from './test/utils';
const isReplaceMD = false;
const START_MARKER = '[//]: # (No deletion!!! Start of Example Replace Section)';
const END_MARKER = '[//]: # (No deletion!!! End of Example Replace Section)';
/**
* Recursively retrieve all `.ts` files in a directory.
*/
function getAllTestFiles(dir: string): string[] {
const entries = fs.readdirSync(dir, { withFileTypes: true });
const files = entries
.filter(file => !file.isDirectory() && file.name.endsWith('.ts'))
.map(file => path.join(dir, file.name));
const directories = entries.filter(entry => entry.isDirectory());
for (const directory of directories) {
files.push(...getAllTestFiles(path.join(dir, directory.name)));
}
return files;
}
/**
* Extract test cases with `@example` from TypeScript files using AST.
*/
function extractExamplesFromFile(filePath: string): { name: string; body: string }[] {
const fileContent = fs.readFileSync(filePath, 'utf-8');
const sourceFile = ts.createSourceFile(filePath, fileContent, ts.ScriptTarget.Latest, true);
const examples: { name: string; body: string }[] = [];
function visit(node: ts.Node) {
if (
ts.isCallExpression(node) && // Ensure it's a function call
node.arguments.length >= 2 && // At least two arguments
ts.isStringLiteral(node.arguments[0]) && // First argument is a string
node.arguments[0].text.startsWith('@example') && // Matches @example
ts.isArrowFunction(node.arguments[1]) // Second argument is an arrow function
) {
const exampleName = node.arguments[0].text.replace('@example ', '').trim();
const bodyNode = node.arguments[1].body;
let exampleBody: string;
if (ts.isBlock(bodyNode)) {
// If it's a block, remove outer {}
exampleBody = bodyNode.statements
.map(stmt => stmt.getFullText(sourceFile))
.join('')
.trim();
} else {
// If it's a single expression, use it directly
exampleBody = bodyNode.getFullText(sourceFile).trim();
}
const transformedBody = exampleBody
.replace(
/expect\((.*?)\)\.(toBeUndefined|toBeNull)\(\);/g,
(match, actual, method) => {
const expectedValue = method === 'toBeUndefined' ? 'undefined' : 'null';
return `console.log(${actual}); // ${expectedValue}`;
}
)
.replace(
/expect\((.*?)\)\.(toEqual|toBe|toStrictEqual|toHaveLength|toMatchObject)\((.*?)\);/gs, // Use `s` flag for multiline
(match, actual, method, expected) => {
expected = expected.replace(/\n/g, '\n //')
return `console.log(${actual}); // ${expected}`;
}
)
.trim();
examples.push({ name: exampleName, body: transformedBody });
}
ts.forEachChild(node, visit);
}
visit(sourceFile);
return examples;
}
/**
* Add examples to the corresponding class in the source file.
*/
function addExamplesToSourceFile(
sourceFilePath: string,
className: string,
examples: { name: string; body: string }[]
): void {
if (!fs.existsSync(sourceFilePath)) {
console.warn(`Source file not found: ${sourceFilePath}`);
return;
}
const sourceContent = fs.readFileSync(sourceFilePath, 'utf-8');
const sourceFile = ts.createSourceFile(sourceFilePath, sourceContent, ts.ScriptTarget.Latest, true);
let updatedContent = sourceContent;
const classNode = sourceFile.statements.find(
stmt => ts.isClassDeclaration(stmt) && stmt.name?.text === className
) as ts.ClassDeclaration | undefined;
if (classNode) {
const classStart = classNode.getStart(sourceFile);
const classEnd = classNode.getEnd();
const classText = classNode.getFullText(sourceFile);
// Extract annotation content
const existingCommentMatch = classText.match(/\/\*\*([\s\S]*?)\*\//);
if (!existingCommentMatch) {
console.warn(`No existing comment found for class: ${className}`);
return;
}
const existingCommentInner = existingCommentMatch[1].replace(/^\n \* /, ''); // Extract comment content (excluding `/**` and `*/`)
// Replace @example part
const exampleSection = examples
.map(
example =>
` * @example \n * \/\/ ${example.name} \n${example.body
.split('\n')
.map(line => ` * ${line}`)
.join('\n')}`
)
.join('\n') + '\n ';
let newComment = '';
if (existingCommentInner.includes('@example')) {
newComment = existingCommentInner.replace(/ \* @example[\s\S]*?(?=\*\/|$)/g, exampleSection);
} else {
newComment = existingCommentInner + `${exampleSection}`;
}
// Replace original content
updatedContent =
sourceContent.slice(0, classStart - existingCommentInner.length - 3) +
newComment +
classText.slice(existingCommentMatch[0].length).trim() +
sourceContent.slice(classEnd);
}
fs.writeFileSync(sourceFilePath, updatedContent, 'utf-8');
console.log(`Updated examples in ${sourceFilePath}`);
}
/**
* Process all test files and update README.md and source files.
*/
function updateExamples(testDir: string, readmePath: string, sourceBaseDir: string): void {
const testFiles = getAllTestFiles(testDir);
let allExamples: string[] = [];
for (const file of testFiles) {
const examples = extractExamplesFromFile(file);
if (examples.length === 0) {
console.log(`No @example found in test file: ${file}`);
continue;
}
const relativePath = path.relative(testDir, file);
const sourceFilePath = path.resolve(sourceBaseDir, relativePath.replace('.test.ts', '.ts'));
const className = path.basename(sourceFilePath, '.ts');
addExamplesToSourceFile(sourceFilePath, toPascalCase(className), examples);
allExamples = allExamples.concat(
examples.map(example => `### ${example.name}\n\`\`\`typescript\n${example.body}\n\`\`\``)
);
}
if (isReplaceMD && allExamples.length > 0) {
replaceExamplesInReadme(readmePath, allExamples);
}
}
/**
* Replace content between markers in README.md.
*/
function replaceExamplesInReadme(readmePath: string, newExamples: string[]): void {
const readmeContent = fs.readFileSync(readmePath, 'utf-8');
const startIdx = readmeContent.indexOf(START_MARKER);
const endIdx = readmeContent.indexOf(END_MARKER);
if (startIdx === -1 || endIdx === -1) {
throw new Error(`Markers not found in ${readmePath}`);
}
const before = readmeContent.slice(0, startIdx + START_MARKER.length);
const after = readmeContent.slice(endIdx);
const updatedContent = `${before}\n\n${newExamples.join('\n\n')}\n\n${after}`;
fs.writeFileSync(readmePath, updatedContent, 'utf-8');
console.log(`README.md updated with new examples.`);
}
// Run the script
const testDir = path.resolve(__dirname, 'test/unit');
const readmePath = path.resolve(__dirname, 'README.md');
const sourceBaseDir = path.resolve(__dirname, 'src');
updateExamples(testDir, readmePath, sourceBaseDir);