data-structure-typed 1.53.2 → 1.53.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -457,3 +457,176 @@ describe('FibonacciHeap Stress Test', () => {
457
457
  );
458
458
  });
459
459
  });
460
+
461
+ describe('classic use', () => {
462
+ it('@example Use Heap to sort an array', () => {
463
+ function heapSort(arr: number[]): number[] {
464
+ const heap = new Heap<number>(arr, { comparator: (a, b) => a - b });
465
+ const sorted: number[] = [];
466
+ while (!heap.isEmpty()) {
467
+ sorted.push(heap.poll()!); // Poll minimum element
468
+ }
469
+ return sorted;
470
+ }
471
+
472
+ const array = [5, 3, 8, 4, 1, 2];
473
+ expect(heapSort(array)).toEqual([1, 2, 3, 4, 5, 8]);
474
+ });
475
+
476
+ it('@example Use Heap to solve top k problems', () => {
477
+ function topKElements(arr: number[], k: number): number[] {
478
+ const heap = new Heap<number>([], { comparator: (a, b) => b - a }); // Max heap
479
+ arr.forEach(num => {
480
+ heap.add(num);
481
+ if (heap.size > k) heap.poll(); // Keep the heap size at K
482
+ });
483
+ return heap.toArray();
484
+ }
485
+
486
+ const numbers = [10, 30, 20, 5, 15, 25];
487
+ expect(topKElements(numbers, 3)).toEqual([15, 10, 5]);
488
+ });
489
+
490
+ it('@example Use Heap to merge sorted sequences', () => {
491
+ function mergeSortedSequences(sequences: number[][]): number[] {
492
+ const heap = new Heap<{ value: number; seqIndex: number; itemIndex: number }>([], {
493
+ comparator: (a, b) => a.value - b.value // Min heap
494
+ });
495
+
496
+ // Initialize heap
497
+ sequences.forEach((seq, seqIndex) => {
498
+ if (seq.length) {
499
+ heap.add({ value: seq[0], seqIndex, itemIndex: 0 });
500
+ }
501
+ });
502
+
503
+ const merged: number[] = [];
504
+ while (!heap.isEmpty()) {
505
+ const { value, seqIndex, itemIndex } = heap.poll()!;
506
+ merged.push(value);
507
+
508
+ if (itemIndex + 1 < sequences[seqIndex].length) {
509
+ heap.add({
510
+ value: sequences[seqIndex][itemIndex + 1],
511
+ seqIndex,
512
+ itemIndex: itemIndex + 1
513
+ });
514
+ }
515
+ }
516
+
517
+ return merged;
518
+ }
519
+
520
+ const sequences = [
521
+ [1, 4, 7],
522
+ [2, 5, 8],
523
+ [3, 6, 9]
524
+ ];
525
+ expect(mergeSortedSequences(sequences)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);
526
+ });
527
+
528
+ it('@example Use Heap to dynamically maintain the median', () => {
529
+ class MedianFinder {
530
+ private low: MaxHeap<number>; // Max heap, stores the smaller half
531
+ private high: MinHeap<number>; // Min heap, stores the larger half
532
+
533
+ constructor() {
534
+ this.low = new MaxHeap<number>([]);
535
+ this.high = new MinHeap<number>([]);
536
+ }
537
+
538
+ addNum(num: number): void {
539
+ if (this.low.isEmpty() || num <= this.low.peek()!) this.low.add(num);
540
+ else this.high.add(num);
541
+
542
+ // Balance heaps
543
+ if (this.low.size > this.high.size + 1) this.high.add(this.low.poll()!);
544
+ else if (this.high.size > this.low.size) this.low.add(this.high.poll()!);
545
+ }
546
+
547
+ findMedian(): number {
548
+ if (this.low.size === this.high.size) return (this.low.peek()! + this.high.peek()!) / 2;
549
+ return this.low.peek()!;
550
+ }
551
+ }
552
+
553
+ const medianFinder = new MedianFinder();
554
+ medianFinder.addNum(10);
555
+ expect(medianFinder.findMedian()).toBe(10);
556
+ medianFinder.addNum(20);
557
+ expect(medianFinder.findMedian()).toBe(15);
558
+ medianFinder.addNum(30);
559
+ expect(medianFinder.findMedian()).toBe(20);
560
+ medianFinder.addNum(40);
561
+ expect(medianFinder.findMedian()).toBe(25);
562
+ medianFinder.addNum(50);
563
+ expect(medianFinder.findMedian()).toBe(30);
564
+ });
565
+
566
+ it('@example Use Heap for load balancing', () => {
567
+ function loadBalance(requests: number[], servers: number): number[] {
568
+ const serverHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // min heap
569
+ const serverLoads = new Array(servers).fill(0);
570
+
571
+ for (let i = 0; i < servers; i++) {
572
+ serverHeap.add({ id: i, load: 0 });
573
+ }
574
+
575
+ requests.forEach(req => {
576
+ const server = serverHeap.poll()!;
577
+ serverLoads[server.id] += req;
578
+ server.load += req;
579
+ serverHeap.add(server); // The server after updating the load is re-entered into the heap
580
+ });
581
+
582
+ return serverLoads;
583
+ }
584
+
585
+ const requests = [5, 2, 8, 3, 7];
586
+ expect(loadBalance(requests, 3)).toEqual([12, 8, 5]);
587
+ });
588
+
589
+ it('@example Use Heap to schedule tasks', () => {
590
+ type Task = [string, number];
591
+
592
+ function scheduleTasks(tasks: Task[], machines: number): Map<number, Task[]> {
593
+ const machineHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // Min heap
594
+ const allocation = new Map<number, Task[]>();
595
+
596
+ // Initialize the load on each machine
597
+ for (let i = 0; i < machines; i++) {
598
+ machineHeap.add({ id: i, load: 0 });
599
+ allocation.set(i, []);
600
+ }
601
+
602
+ // Assign tasks
603
+ tasks.forEach(([task, load]) => {
604
+ const machine = machineHeap.poll()!;
605
+ allocation.get(machine.id)!.push([task, load]);
606
+ machine.load += load;
607
+ machineHeap.add(machine); // The machine after updating the load is re-entered into the heap
608
+ });
609
+
610
+ return allocation;
611
+ }
612
+
613
+ const tasks: Task[] = [
614
+ ['Task1', 3],
615
+ ['Task2', 1],
616
+ ['Task3', 2],
617
+ ['Task4', 5],
618
+ ['Task5', 4]
619
+ ];
620
+ const expectedMap = new Map<number, Task[]>();
621
+ expectedMap.set(0, [
622
+ ['Task1', 3],
623
+ ['Task4', 5]
624
+ ]);
625
+ expectedMap.set(1, [
626
+ ['Task2', 1],
627
+ ['Task3', 2],
628
+ ['Task5', 4]
629
+ ]);
630
+ expect(scheduleTasks(tasks, 2)).toEqual(expectedMap);
631
+ });
632
+ });
@@ -502,3 +502,437 @@ describe('iterable methods', () => {
502
502
  expect(dl.some(value => value > 100)).toBe(false);
503
503
  });
504
504
  });
505
+
506
+ describe('classic use', () => {
507
+ it('@example text editor operation history', () => {
508
+ const actions = [
509
+ { type: 'insert', content: 'first line of text' },
510
+ { type: 'insert', content: 'second line of text' },
511
+ { type: 'delete', content: 'delete the first line' }
512
+ ];
513
+ const editorHistory = new DoublyLinkedList<{ type: string; content: string }>(actions);
514
+
515
+ expect(editorHistory.last?.type).toBe('delete');
516
+ expect(editorHistory.pop()?.content).toBe('delete the first line');
517
+ expect(editorHistory.last?.type).toBe('insert');
518
+ });
519
+
520
+ it('@example Browser history', () => {
521
+ const browserHistory = new DoublyLinkedList<string>();
522
+
523
+ browserHistory.push('home page');
524
+ browserHistory.push('search page');
525
+ browserHistory.push('details page');
526
+
527
+ expect(browserHistory.last).toBe('details page');
528
+ expect(browserHistory.pop()).toBe('details page');
529
+ expect(browserHistory.last).toBe('search page');
530
+ });
531
+
532
+ it('@example Use DoublyLinkedList to implement music player', () => {
533
+ // Define the Song interface
534
+ interface Song {
535
+ title: string;
536
+ artist: string;
537
+ duration: number; // duration in seconds
538
+ }
539
+
540
+ class Player {
541
+ private playlist: DoublyLinkedList<Song>;
542
+ private currentSong: ReturnType<typeof this.playlist.getNodeAt> | undefined;
543
+
544
+ constructor(songs: Song[]) {
545
+ this.playlist = new DoublyLinkedList<Song>();
546
+ songs.forEach(song => this.playlist.push(song));
547
+ this.currentSong = this.playlist.head;
548
+ }
549
+
550
+ // Play the next song in the playlist
551
+ playNext(): Song | undefined {
552
+ if (!this.currentSong?.next) {
553
+ this.currentSong = this.playlist.head; // Loop to the first song
554
+ } else {
555
+ this.currentSong = this.currentSong.next;
556
+ }
557
+ return this.currentSong?.value;
558
+ }
559
+
560
+ // Play the previous song in the playlist
561
+ playPrevious(): Song | undefined {
562
+ if (!this.currentSong?.prev) {
563
+ this.currentSong = this.playlist.tail; // Loop to the last song
564
+ } else {
565
+ this.currentSong = this.currentSong.prev;
566
+ }
567
+ return this.currentSong?.value;
568
+ }
569
+
570
+ // Get the current song
571
+ getCurrentSong(): Song | undefined {
572
+ return this.currentSong?.value;
573
+ }
574
+
575
+ // Loop through the playlist twice
576
+ loopThroughPlaylist(): Song[] {
577
+ const playedSongs: Song[] = [];
578
+ const initialNode = this.currentSong;
579
+
580
+ // Loop through the playlist twice
581
+ for (let i = 0; i < this.playlist.size * 2; i++) {
582
+ playedSongs.push(this.currentSong!.value);
583
+ this.currentSong = this.currentSong!.next || this.playlist.head; // Loop back to the start if needed
584
+ }
585
+
586
+ // Reset the current song to the initial song
587
+ this.currentSong = initialNode;
588
+ return playedSongs;
589
+ }
590
+ }
591
+
592
+ const songs = [
593
+ { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
594
+ { title: 'Hotel California', artist: 'Eagles', duration: 391 },
595
+ { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
596
+ { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
597
+ ];
598
+ let player = new Player(songs);
599
+ // should play the next song
600
+ player = new Player(songs);
601
+ const firstSong = player.getCurrentSong();
602
+ const nextSong = player.playNext();
603
+
604
+ // Expect the next song to be "Hotel California by Eagles"
605
+ expect(nextSong).toEqual({ title: 'Hotel California', artist: 'Eagles', duration: 391 });
606
+ expect(firstSong).toEqual({ title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 });
607
+
608
+ // should play the previous song
609
+ player = new Player(songs);
610
+ player.playNext(); // Move to the second song
611
+ const currentSong = player.getCurrentSong();
612
+ const previousSong = player.playPrevious();
613
+
614
+ // Expect the previous song to be "Bohemian Rhapsody by Queen"
615
+ expect(previousSong).toEqual({ title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 });
616
+ expect(currentSong).toEqual({ title: 'Hotel California', artist: 'Eagles', duration: 391 });
617
+
618
+ // should loop to the first song when playing next from the last song
619
+ player = new Player(songs);
620
+ player.playNext(); // Move to the second song
621
+ player.playNext(); // Move to the third song
622
+ player.playNext(); // Move to the fourth song
623
+
624
+ const nextSongToFirst = player.playNext(); // Should loop to the first song
625
+
626
+ // Expect the next song to be "Bohemian Rhapsody by Queen"
627
+ expect(nextSongToFirst).toEqual({ title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 });
628
+
629
+ // should loop to the last song when playing previous from the first song
630
+ player = new Player(songs);
631
+ player.playNext(); // Move to the first song
632
+ player.playNext(); // Move to the second song
633
+ player.playNext(); // Move to the third song
634
+ player.playNext(); // Move to the fourth song
635
+
636
+ const previousToLast = player.playPrevious(); // Should loop to the last song
637
+
638
+ // Expect the previous song to be "Billie Jean by Michael Jackson"
639
+ expect(previousToLast).toEqual({ title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 });
640
+
641
+ // should loop through the entire playlist
642
+ player = new Player(songs);
643
+ const playedSongs = player.loopThroughPlaylist();
644
+
645
+ // The expected order of songs for two loops
646
+ expect(playedSongs).toEqual([
647
+ { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
648
+ { title: 'Hotel California', artist: 'Eagles', duration: 391 },
649
+ { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
650
+ { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 },
651
+ { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
652
+ { title: 'Hotel California', artist: 'Eagles', duration: 391 },
653
+ { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
654
+ { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
655
+ ]);
656
+ });
657
+
658
+ it('@example Use DoublyLinkedList to implement LRU cache', () => {
659
+ interface CacheEntry<K, V> {
660
+ key: K;
661
+ value: V;
662
+ }
663
+
664
+ class LRUCache<K = string, V = any> {
665
+ private readonly capacity: number;
666
+ private list: DoublyLinkedList<CacheEntry<K, V>>;
667
+ private map: Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>;
668
+
669
+ constructor(capacity: number) {
670
+ if (capacity <= 0) {
671
+ throw new Error('lru cache capacity must be greater than 0');
672
+ }
673
+ this.capacity = capacity;
674
+ this.list = new DoublyLinkedList<CacheEntry<K, V>>();
675
+ this.map = new Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>();
676
+ }
677
+
678
+ // Get cached value
679
+ get(key: K): V | undefined {
680
+ const node = this.map.get(key);
681
+
682
+ if (!node) return undefined;
683
+
684
+ // Move the visited node to the head of the linked list (most recently used)
685
+ this.moveToFront(node);
686
+
687
+ return node.value.value;
688
+ }
689
+
690
+ // Set cache value
691
+ set(key: K, value: V): void {
692
+ // Check if it already exists
693
+ const node = this.map.get(key);
694
+
695
+ if (node) {
696
+ // Update value and move to head
697
+ node.value.value = value;
698
+ this.moveToFront(node);
699
+ return;
700
+ }
701
+
702
+ // Check capacity
703
+ if (this.list.size >= this.capacity) {
704
+ // Delete the least recently used element (the tail of the linked list)
705
+ const removedNode = this.list.tail;
706
+ if (removedNode) {
707
+ this.map.delete(removedNode.value.key);
708
+ this.list.pop();
709
+ }
710
+ }
711
+
712
+ // Create new node and add to head
713
+ const newEntry: CacheEntry<K, V> = { key, value };
714
+ this.list.unshift(newEntry);
715
+
716
+ // Save node reference in map
717
+ const newNode = this.list.head;
718
+ if (newNode) {
719
+ this.map.set(key, newNode);
720
+ }
721
+ }
722
+
723
+ // Move the node to the head of the linked list
724
+ private moveToFront(node: DoublyLinkedListNode<CacheEntry<K, V>>): void {
725
+ this.list.delete(node);
726
+ this.list.unshift(node.value);
727
+ }
728
+
729
+ // Delete specific key
730
+ delete(key: K): boolean {
731
+ const node = this.map.get(key);
732
+ if (!node) return false;
733
+
734
+ // Remove from linked list
735
+ this.list.delete(node);
736
+ // Remove from map
737
+ this.map.delete(key);
738
+
739
+ return true;
740
+ }
741
+
742
+ // Clear cache
743
+ clear(): void {
744
+ this.list.clear();
745
+ this.map.clear();
746
+ }
747
+
748
+ // Get the current cache size
749
+ get size(): number {
750
+ return this.list.size;
751
+ }
752
+
753
+ // Check if it is empty
754
+ get isEmpty(): boolean {
755
+ return this.list.isEmpty();
756
+ }
757
+ }
758
+
759
+ // should set and get values correctly
760
+ const cache = new LRUCache<string, number>(3);
761
+ cache.set('a', 1);
762
+ cache.set('b', 2);
763
+ cache.set('c', 3);
764
+
765
+ expect(cache.get('a')).toBe(1);
766
+ expect(cache.get('b')).toBe(2);
767
+ expect(cache.get('c')).toBe(3);
768
+
769
+ // The least recently used element should be evicted when capacity is exceeded
770
+ cache.clear();
771
+ cache.set('a', 1);
772
+ cache.set('b', 2);
773
+ cache.set('c', 3);
774
+ cache.set('d', 4); // This will eliminate 'a'
775
+
776
+ expect(cache.get('a')).toBeUndefined();
777
+ expect(cache.get('b')).toBe(2);
778
+ expect(cache.get('c')).toBe(3);
779
+ expect(cache.get('d')).toBe(4);
780
+
781
+ // The priority of an element should be updated when it is accessed
782
+ cache.clear();
783
+ cache.set('a', 1);
784
+ cache.set('b', 2);
785
+ cache.set('c', 3);
786
+
787
+ cache.get('a'); // access 'a'
788
+ cache.set('d', 4); // This will eliminate 'b'
789
+
790
+ expect(cache.get('a')).toBe(1);
791
+ expect(cache.get('b')).toBeUndefined();
792
+ expect(cache.get('c')).toBe(3);
793
+ expect(cache.get('d')).toBe(4);
794
+
795
+ // Should support updating existing keys
796
+ cache.clear();
797
+ cache.set('a', 1);
798
+ cache.set('a', 10);
799
+
800
+ expect(cache.get('a')).toBe(10);
801
+
802
+ // Should support deleting specified keys
803
+ cache.clear();
804
+ cache.set('a', 1);
805
+ cache.set('b', 2);
806
+
807
+ expect(cache.delete('a')).toBe(true);
808
+ expect(cache.get('a')).toBeUndefined();
809
+ expect(cache.size).toBe(1);
810
+
811
+ // Should support clearing cache
812
+ cache.clear();
813
+ cache.set('a', 1);
814
+ cache.set('b', 2);
815
+ cache.clear();
816
+
817
+ expect(cache.size).toBe(0);
818
+ expect(cache.isEmpty).toBe(true);
819
+ });
820
+
821
+ it('@example finding lyrics by timestamp in Coldplay\'s "Fix You"', () => {
822
+ // Create a DoublyLinkedList to store song lyrics with timestamps
823
+ const lyricsList = new DoublyLinkedList<{ time: number; text: string }>();
824
+
825
+ // Detailed lyrics with precise timestamps (in milliseconds)
826
+ const lyrics = [
827
+ { time: 0, text: "When you try your best, but you don't succeed" },
828
+ { time: 4000, text: 'When you get what you want, but not what you need' },
829
+ { time: 8000, text: "When you feel so tired, but you can't sleep" },
830
+ { time: 12000, text: 'Stuck in reverse' },
831
+ { time: 16000, text: 'And the tears come streaming down your face' },
832
+ { time: 20000, text: "When you lose something you can't replace" },
833
+ { time: 24000, text: 'When you love someone, but it goes to waste' },
834
+ { time: 28000, text: 'Could it be worse?' },
835
+ { time: 32000, text: 'Lights will guide you home' },
836
+ { time: 36000, text: 'And ignite your bones' },
837
+ { time: 40000, text: 'And I will try to fix you' }
838
+ ];
839
+
840
+ // Populate the DoublyLinkedList with lyrics
841
+ lyrics.forEach(lyric => lyricsList.push(lyric));
842
+
843
+ // Test different scenarios of lyric synchronization
844
+
845
+ // 1. Find lyric at exact timestamp
846
+ const exactTimeLyric = lyricsList.findBackward(lyric => lyric.time <= 36000);
847
+ expect(exactTimeLyric?.text).toBe('And ignite your bones');
848
+
849
+ // 2. Find lyric between timestamps
850
+ const betweenTimeLyric = lyricsList.findBackward(lyric => lyric.time <= 22000);
851
+ expect(betweenTimeLyric?.text).toBe("When you lose something you can't replace");
852
+
853
+ // 3. Find first lyric when timestamp is less than first entry
854
+ const earlyTimeLyric = lyricsList.findBackward(lyric => lyric.time <= -1000);
855
+ expect(earlyTimeLyric).toBeUndefined();
856
+
857
+ // 4. Find last lyric when timestamp is after last entry
858
+ const lateTimeLyric = lyricsList.findBackward(lyric => lyric.time <= 50000);
859
+ expect(lateTimeLyric?.text).toBe('And I will try to fix you');
860
+ });
861
+
862
+ it('@example cpu process schedules', () => {
863
+ class Process {
864
+ constructor(
865
+ public id: number,
866
+ public priority: number
867
+ ) {}
868
+
869
+ execute(): string {
870
+ return `Process ${this.id} executed.`;
871
+ }
872
+ }
873
+
874
+ class Scheduler {
875
+ private queue: DoublyLinkedList<Process>;
876
+
877
+ constructor() {
878
+ this.queue = new DoublyLinkedList<Process>();
879
+ }
880
+
881
+ addProcess(process: Process): void {
882
+ // Insert processes into a queue based on priority, keeping priority in descending order
883
+ let current = this.queue.head;
884
+ while (current && current.value.priority >= process.priority) {
885
+ current = current.next;
886
+ }
887
+
888
+ if (!current) {
889
+ this.queue.push(process);
890
+ } else {
891
+ this.queue.addBefore(current, process);
892
+ }
893
+ }
894
+
895
+ executeNext(): string | undefined {
896
+ // Execute tasks at the head of the queue in order
897
+ const process = this.queue.shift();
898
+ return process ? process.execute() : undefined;
899
+ }
900
+
901
+ listProcesses(): string[] {
902
+ return this.queue.toArray().map(process => `Process ${process.id} (Priority: ${process.priority})`);
903
+ }
904
+
905
+ clear(): void {
906
+ this.queue.clear();
907
+ }
908
+ }
909
+
910
+ // should add processes based on priority
911
+ let scheduler = new Scheduler();
912
+ scheduler.addProcess(new Process(1, 10));
913
+ scheduler.addProcess(new Process(2, 20));
914
+ scheduler.addProcess(new Process(3, 15));
915
+
916
+ expect(scheduler.listProcesses()).toEqual([
917
+ 'Process 2 (Priority: 20)',
918
+ 'Process 3 (Priority: 15)',
919
+ 'Process 1 (Priority: 10)'
920
+ ]);
921
+
922
+ // should execute the highest priority process
923
+ scheduler = new Scheduler();
924
+ scheduler.addProcess(new Process(1, 10));
925
+ scheduler.addProcess(new Process(2, 20));
926
+
927
+ expect(scheduler.executeNext()).toBe('Process 2 executed.');
928
+ expect(scheduler.listProcesses()).toEqual(['Process 1 (Priority: 10)']);
929
+
930
+ // should clear all processes
931
+ scheduler = new Scheduler();
932
+ scheduler.addProcess(new Process(1, 10));
933
+ scheduler.addProcess(new Process(2, 20));
934
+
935
+ scheduler.clear();
936
+ expect(scheduler.listProcesses()).toEqual([]);
937
+ });
938
+ });
@@ -1 +1,49 @@
1
- export {};
1
+ /**
2
+ * Convert any string to CamelCase format
3
+ */
4
+ export function toCamelCase(str: string): string {
5
+ return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (_, chr) => chr.toUpperCase());
6
+ }
7
+
8
+ /**
9
+ * Convert any string to SnakeCase format
10
+ */
11
+ export function toSnakeCase(str: string): string {
12
+ return str
13
+ .replace(/([a-z])([A-Z])/g, '$1_$2') // Add underline between lowercase and uppercase letters
14
+ .toLowerCase() // Convert to lowercase
15
+ .replace(/[^a-z0-9]+/g, '_'); // Replace non-alphanumeric characters with underscores
16
+ }
17
+
18
+ /**
19
+ * Convert any string to PascalCase format (first letter capitalized)
20
+ */
21
+ export function toPascalCase(str: string): string {
22
+ return str
23
+ .replace(/([a-z])([A-Z])/g, '$1 $2') // Add space between lowercase and uppercase letters
24
+ .replace(/[^a-zA-Z0-9]+/g, ' ') // Replace non-alphanumeric characters with spaces
25
+ .split(' ') // Separate strings by spaces
26
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) // The first letter is capitalized, the rest are lowercase
27
+ .join(''); // Combine into a string
28
+ }
29
+
30
+ /**
31
+ * Convert CamelCase or SnakeCase string to string format with specified separator
32
+ */
33
+ export function toSeparatedCase(str: string, separator: string = '_'): string {
34
+ return str
35
+ .replace(/([a-z0-9])([A-Z])/g, '$1' + separator + '$2')
36
+ .replace(/[_\s]+/g, separator)
37
+ .toLowerCase();
38
+ }
39
+
40
+ /**
41
+ * Convert the string to all uppercase and delimit it using the specified delimiter
42
+ */
43
+ export function toUpperSeparatedCase(str: string, separator: string = '_'): string {
44
+ return str
45
+ .toUpperCase() // Convert all letters to uppercase
46
+ .replace(/([a-z0-9])([A-Z])/g, '$1' + separator + '$2') // Add separator between lowercase letters and uppercase letters
47
+ .replace(/[^A-Z0-9]+/g, separator) // Replace non-alphanumeric characters with separators
48
+ .replace(new RegExp(`^${separator}|${separator}$`, 'g'), ''); // Remove the starting and ending separators
49
+ }