data-structure-typed 2.0.0 → 2.0.2

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/dist/cjs/data-structures/binary-tree/binary-tree.js +8 -9
  3. package/dist/cjs/data-structures/binary-tree/binary-tree.js.map +1 -1
  4. package/dist/cjs/data-structures/graph/abstract-graph.js +14 -14
  5. package/dist/cjs/data-structures/graph/abstract-graph.js.map +1 -1
  6. package/dist/cjs/data-structures/hash/hash-map.d.ts +46 -0
  7. package/dist/cjs/data-structures/hash/hash-map.js +46 -0
  8. package/dist/cjs/data-structures/hash/hash-map.js.map +1 -1
  9. package/dist/cjs/data-structures/linked-list/singly-linked-list.d.ts +66 -0
  10. package/dist/cjs/data-structures/linked-list/singly-linked-list.js +66 -0
  11. package/dist/cjs/data-structures/linked-list/singly-linked-list.js.map +1 -1
  12. package/dist/cjs/data-structures/queue/queue.d.ts +47 -0
  13. package/dist/cjs/data-structures/queue/queue.js +47 -0
  14. package/dist/cjs/data-structures/queue/queue.js.map +1 -1
  15. package/dist/cjs/data-structures/stack/stack.d.ts +121 -0
  16. package/dist/cjs/data-structures/stack/stack.js +121 -0
  17. package/dist/cjs/data-structures/stack/stack.js.map +1 -1
  18. package/dist/cjs/types/utils/utils.d.ts +1 -7
  19. package/dist/cjs/utils/utils.d.ts +3 -49
  20. package/dist/cjs/utils/utils.js +13 -82
  21. package/dist/cjs/utils/utils.js.map +1 -1
  22. package/dist/esm/data-structures/binary-tree/binary-tree.js +8 -9
  23. package/dist/esm/data-structures/binary-tree/binary-tree.js.map +1 -1
  24. package/dist/esm/data-structures/graph/abstract-graph.js +14 -14
  25. package/dist/esm/data-structures/graph/abstract-graph.js.map +1 -1
  26. package/dist/esm/data-structures/hash/hash-map.d.ts +46 -0
  27. package/dist/esm/data-structures/hash/hash-map.js +46 -0
  28. package/dist/esm/data-structures/hash/hash-map.js.map +1 -1
  29. package/dist/esm/data-structures/linked-list/singly-linked-list.d.ts +66 -0
  30. package/dist/esm/data-structures/linked-list/singly-linked-list.js +66 -0
  31. package/dist/esm/data-structures/linked-list/singly-linked-list.js.map +1 -1
  32. package/dist/esm/data-structures/queue/queue.d.ts +47 -0
  33. package/dist/esm/data-structures/queue/queue.js +47 -0
  34. package/dist/esm/data-structures/queue/queue.js.map +1 -1
  35. package/dist/esm/data-structures/stack/stack.d.ts +121 -0
  36. package/dist/esm/data-structures/stack/stack.js +121 -0
  37. package/dist/esm/data-structures/stack/stack.js.map +1 -1
  38. package/dist/esm/types/utils/utils.d.ts +1 -7
  39. package/dist/esm/utils/utils.d.ts +3 -49
  40. package/dist/esm/utils/utils.js +10 -68
  41. package/dist/esm/utils/utils.js.map +1 -1
  42. package/dist/umd/data-structure-typed.js +32 -80
  43. package/dist/umd/data-structure-typed.min.js +2 -2
  44. package/dist/umd/data-structure-typed.min.js.map +1 -1
  45. package/package.json +2 -2
  46. package/src/data-structures/binary-tree/binary-tree.ts +9 -10
  47. package/src/data-structures/graph/abstract-graph.ts +14 -14
  48. package/src/data-structures/hash/hash-map.ts +46 -0
  49. package/src/data-structures/linked-list/singly-linked-list.ts +66 -0
  50. package/src/data-structures/queue/queue.ts +47 -0
  51. package/src/data-structures/stack/stack.ts +121 -0
  52. package/src/types/utils/utils.ts +1 -6
  53. package/src/utils/utils.ts +11 -83
  54. package/test/unit/data-structures/graph/directed-graph.test.ts +37 -37
  55. package/test/unit/data-structures/graph/undirected-graph.test.ts +2 -2
  56. package/test/unit/data-structures/hash/hash-map.test.ts +135 -0
  57. package/test/unit/data-structures/linked-list/singly-linked-list.test.ts +72 -1
  58. package/test/unit/data-structures/queue/queue.test.ts +214 -0
  59. package/test/unit/data-structures/stack/stack.test.ts +165 -0
  60. package/test/unit/utils/utils.test.ts +35 -2
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "data-structure-typed",
3
- "version": "2.0.0",
4
- "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",
3
+ "version": "2.0.2",
4
+ "description": "Standard data structure",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",
7
7
  "browser": "dist/umd/data-structure-typed.min.js",
@@ -20,7 +20,7 @@ import type {
20
20
  NodeDisplayLayout,
21
21
  NodePredicate,
22
22
  OptNodeOrNull,
23
- RBTNColor,
23
+ RBTNColor, Thunk,
24
24
  ToEntryFn
25
25
  } from '../../types';
26
26
  import { IBinaryTree } from '../../interfaces';
@@ -1304,12 +1304,12 @@ export class BinaryTree<K = any, V = any, R = object, MK = any, MV = any, MR = o
1304
1304
  return callback(dfs(startNode));
1305
1305
  } else {
1306
1306
  // Indirect implementation of iteration using tail recursion optimization
1307
- const dfs = trampoline((cur: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> => {
1307
+ const dfs = (cur: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> | Thunk<BinaryTreeNode<K, V>> => {
1308
1308
  if (!this.isRealNode(cur.left)) return cur;
1309
- return dfs.cont(cur.left);
1310
- });
1309
+ return () => dfs(cur.left!);
1310
+ };
1311
1311
 
1312
- return callback(dfs(startNode));
1312
+ return callback(trampoline(() => dfs(startNode)));
1313
1313
  }
1314
1314
  }
1315
1315
 
@@ -1352,13 +1352,12 @@ export class BinaryTree<K = any, V = any, R = object, MK = any, MV = any, MR = o
1352
1352
 
1353
1353
  return callback(dfs(startNode));
1354
1354
  } else {
1355
- // Indirect implementation of iteration using tail recursion optimization
1356
- const dfs = trampoline((cur: BinaryTreeNode<K, V>) => {
1355
+ const dfs = (cur: BinaryTreeNode<K, V>) => {
1357
1356
  if (!this.isRealNode(cur.right)) return cur;
1358
- return dfs.cont(cur.right);
1359
- });
1357
+ return () => dfs(cur.right!) as Thunk<BinaryTreeNode<K, V>>;
1358
+ };
1360
1359
 
1361
- return callback(dfs(startNode));
1360
+ return callback(trampoline(() => dfs(startNode)));
1362
1361
  }
1363
1362
  }
1364
1363
 
@@ -339,7 +339,7 @@ export abstract class AbstractGraph<
339
339
 
340
340
  if (isWeight) {
341
341
  const allPaths = this.getAllPathsBetween(v1, v2);
342
- let min = Infinity;
342
+ let min = Number.MAX_SAFE_INTEGER;
343
343
  for (const path of allPaths) {
344
344
  min = Math.min(this.getPathSumWeight(path), min);
345
345
  }
@@ -404,7 +404,7 @@ export abstract class AbstractGraph<
404
404
  if (isWeight) {
405
405
  if (isDFS) {
406
406
  const allPaths = this.getAllPathsBetween(v1, v2, 10000);
407
- let min = Infinity;
407
+ let min = Number.MAX_SAFE_INTEGER;
408
408
  let minIndex = -1;
409
409
  let index = 0;
410
410
  for (const path of allPaths) {
@@ -475,7 +475,7 @@ export abstract class AbstractGraph<
475
475
  getMinDist: boolean = false,
476
476
  genPaths: boolean = false
477
477
  ): DijkstraResult<VO> {
478
- let minDist = Infinity;
478
+ let minDist = Number.MAX_SAFE_INTEGER;
479
479
  let minDest: VO | undefined = undefined;
480
480
  let minPath: VO[] = [];
481
481
  const paths: VO[][] = [];
@@ -494,13 +494,13 @@ export abstract class AbstractGraph<
494
494
 
495
495
  for (const vertex of vertexMap) {
496
496
  const vertexOrKey = vertex[1];
497
- if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Infinity);
497
+ if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);
498
498
  }
499
499
  distMap.set(srcVertex, 0);
500
500
  preMap.set(srcVertex, undefined);
501
501
 
502
502
  const getMinOfNoSeen = () => {
503
- let min = Infinity;
503
+ let min = Number.MAX_SAFE_INTEGER;
504
504
  let minV: VO | undefined = undefined;
505
505
  for (const [key, value] of distMap) {
506
506
  if (!seen.has(key)) {
@@ -537,7 +537,7 @@ export abstract class AbstractGraph<
537
537
  seen.add(cur);
538
538
  if (destVertex && destVertex === cur) {
539
539
  if (getMinDist) {
540
- minDist = distMap.get(destVertex) || Infinity;
540
+ minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;
541
541
  }
542
542
  if (genPaths) {
543
543
  getPaths(destVertex);
@@ -605,7 +605,7 @@ export abstract class AbstractGraph<
605
605
  getMinDist: boolean = false,
606
606
  genPaths: boolean = false
607
607
  ): DijkstraResult<VO> {
608
- let minDist = Infinity;
608
+ let minDist = Number.MAX_SAFE_INTEGER;
609
609
  let minDest: VO | undefined = undefined;
610
610
  let minPath: VO[] = [];
611
611
  const paths: VO[][] = [];
@@ -621,7 +621,7 @@ export abstract class AbstractGraph<
621
621
 
622
622
  for (const vertex of vertexMap) {
623
623
  const vertexOrKey = vertex[1];
624
- if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Infinity);
624
+ if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);
625
625
  }
626
626
 
627
627
  const heap = new Heap<{ key: number; value: VO }>([], { comparator: (a, b) => a.key - b.key });
@@ -661,7 +661,7 @@ export abstract class AbstractGraph<
661
661
  seen.add(cur);
662
662
  if (destVertex && destVertex === cur) {
663
663
  if (getMinDist) {
664
- minDist = distMap.get(destVertex) || Infinity;
664
+ minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;
665
665
  }
666
666
  if (genPaths) {
667
667
  getPaths(destVertex);
@@ -732,7 +732,7 @@ export abstract class AbstractGraph<
732
732
  const paths: VO[][] = [];
733
733
  const distMap: Map<VO, number> = new Map();
734
734
  const preMap: Map<VO, VO> = new Map(); // predecessor
735
- let min = Infinity;
735
+ let min = Number.MAX_SAFE_INTEGER;
736
736
  let minPath: VO[] = [];
737
737
  // TODO
738
738
  let hasNegativeCycle: boolean | undefined;
@@ -745,7 +745,7 @@ export abstract class AbstractGraph<
745
745
  const numOfEdges = edgeMap.length;
746
746
 
747
747
  this._vertexMap.forEach(vertex => {
748
- distMap.set(vertex, Infinity);
748
+ distMap.set(vertex, Number.MAX_SAFE_INTEGER);
749
749
  });
750
750
 
751
751
  distMap.set(srcVertex, 0);
@@ -759,7 +759,7 @@ export abstract class AbstractGraph<
759
759
  const sWeight = distMap.get(s);
760
760
  const dWeight = distMap.get(d);
761
761
  if (sWeight !== undefined && dWeight !== undefined) {
762
- if (distMap.get(s) !== Infinity && sWeight + weight < dWeight) {
762
+ if (distMap.get(s) !== Number.MAX_SAFE_INTEGER && sWeight + weight < dWeight) {
763
763
  distMap.set(d, sWeight + weight);
764
764
  if (genPath) preMap.set(d, s);
765
765
  }
@@ -804,7 +804,7 @@ export abstract class AbstractGraph<
804
804
  const weight = edgeMap[j].weight;
805
805
  const sWeight = distMap.get(s);
806
806
  if (sWeight) {
807
- if (sWeight !== Infinity && sWeight + weight < sWeight) hasNegativeCycle = true;
807
+ if (sWeight !== Number.MAX_SAFE_INTEGER && sWeight + weight < sWeight) hasNegativeCycle = true;
808
808
  }
809
809
  }
810
810
  }
@@ -860,7 +860,7 @@ export abstract class AbstractGraph<
860
860
 
861
861
  for (let i = 0; i < n; i++) {
862
862
  for (let j = 0; j < n; j++) {
863
- costs[i][j] = this.getEdge(idAndVertices[i][1], idAndVertices[j][1])?.weight || Infinity;
863
+ costs[i][j] = this.getEdge(idAndVertices[i][1], idAndVertices[j][1])?.weight || Number.MAX_SAFE_INTEGER;
864
864
  }
865
865
  }
866
866
 
@@ -21,6 +21,52 @@ import { isWeakKey, rangeCheck } from '../../utils';
21
21
  * 3. Unique Keys: Keys are unique.
22
22
  * If you try to insert another entry with the same key, the new one will replace the old entry.
23
23
  * 4. Unordered Collection: HashMap does not guarantee the order of entries, and the order may change over time.
24
+ * @example
25
+ * // should maintain insertion order
26
+ * const linkedHashMap = new LinkedHashMap<number, string>();
27
+ * linkedHashMap.set(1, 'A');
28
+ * linkedHashMap.set(2, 'B');
29
+ * linkedHashMap.set(3, 'C');
30
+ *
31
+ * const result = Array.from(linkedHashMap);
32
+ * console.log(result); // [
33
+ * // [1, 'A'],
34
+ * // [2, 'B'],
35
+ * // [3, 'C']
36
+ * // ]
37
+ * @example
38
+ * // fast lookup of values by key
39
+ * const hashMap = new HashMap<number, string>();
40
+ * hashMap.set(1, 'A');
41
+ * hashMap.set(2, 'B');
42
+ * hashMap.set(3, 'C');
43
+ *
44
+ * console.log(hashMap.get(1)); // 'A'
45
+ * console.log(hashMap.get(2)); // 'B'
46
+ * console.log(hashMap.get(3)); // 'C'
47
+ * console.log(hashMap.get(99)); // undefined
48
+ * @example
49
+ * // remove duplicates when adding multiple entries
50
+ * const hashMap = new HashMap<number, string>();
51
+ * hashMap.set(1, 'A');
52
+ * hashMap.set(2, 'B');
53
+ * hashMap.set(1, 'C'); // Update value for key 1
54
+ *
55
+ * console.log(hashMap.size); // 2
56
+ * console.log(hashMap.get(1)); // 'C'
57
+ * console.log(hashMap.get(2)); // 'B'
58
+ * @example
59
+ * // count occurrences of keys
60
+ * const data = [1, 2, 1, 3, 2, 1];
61
+ *
62
+ * const countMap = new HashMap<number, number>();
63
+ * for (const key of data) {
64
+ * countMap.set(key, (countMap.get(key) || 0) + 1);
65
+ * }
66
+ *
67
+ * console.log(countMap.get(1)); // 3
68
+ * console.log(countMap.get(2)); // 2
69
+ * console.log(countMap.get(3)); // 1
24
70
  */
25
71
  export class HashMap<K = any, V = any, R = [K, V]> extends IterableEntryBase<K, V> {
26
72
  /**
@@ -38,6 +38,72 @@ export class SinglyLinkedListNode<E = any> extends LinkedListNode<E> {
38
38
  * 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.
39
39
  * Caution: Although our linked list classes provide methods such as at, setAt, addAt, and indexOf that are based on array indices, their time complexity, like that of the native Array.lastIndexOf, is 𝑂(𝑛). If you need to use these methods frequently, you might want to consider other data structures, such as Deque or Queue (designed for random access). Similarly, since the native Array.shift method has a time complexity of 𝑂(𝑛), using an array to simulate a queue can be inefficient. In such cases, you should use Queue or Deque, as these data structures leverage deferred array rearrangement, effectively reducing the average time complexity to 𝑂(1).
40
40
  *
41
+ * @example
42
+ * // implementation of a basic text editor
43
+ * class TextEditor {
44
+ * private content: SinglyLinkedList<string>;
45
+ * private cursorIndex: number;
46
+ * private undoStack: Stack<{ operation: string; data?: any }>;
47
+ *
48
+ * constructor() {
49
+ * this.content = new SinglyLinkedList<string>();
50
+ * this.cursorIndex = 0; // Cursor starts at the beginning
51
+ * this.undoStack = new Stack<{ operation: string; data?: any }>(); // Stack to keep track of operations for undo
52
+ * }
53
+ *
54
+ * insert(char: string) {
55
+ * this.content.addAt(this.cursorIndex, char);
56
+ * this.cursorIndex++;
57
+ * this.undoStack.push({ operation: 'insert', data: { index: this.cursorIndex - 1 } });
58
+ * }
59
+ *
60
+ * delete() {
61
+ * if (this.cursorIndex === 0) return; // Nothing to delete
62
+ * const deleted = this.content.deleteAt(this.cursorIndex - 1);
63
+ * this.cursorIndex--;
64
+ * this.undoStack.push({ operation: 'delete', data: { index: this.cursorIndex, char: deleted } });
65
+ * }
66
+ *
67
+ * moveCursor(index: number) {
68
+ * this.cursorIndex = Math.max(0, Math.min(index, this.content.length));
69
+ * }
70
+ *
71
+ * undo() {
72
+ * if (this.undoStack.size === 0) return; // No operations to undo
73
+ * const lastAction = this.undoStack.pop();
74
+ *
75
+ * if (lastAction!.operation === 'insert') {
76
+ * this.content.deleteAt(lastAction!.data.index);
77
+ * this.cursorIndex = lastAction!.data.index;
78
+ * } else if (lastAction!.operation === 'delete') {
79
+ * this.content.addAt(lastAction!.data.index, lastAction!.data.char);
80
+ * this.cursorIndex = lastAction!.data.index + 1;
81
+ * }
82
+ * }
83
+ *
84
+ * getText(): string {
85
+ * return [...this.content].join('');
86
+ * }
87
+ * }
88
+ *
89
+ * // Example Usage
90
+ * const editor = new TextEditor();
91
+ * editor.insert('H');
92
+ * editor.insert('e');
93
+ * editor.insert('l');
94
+ * editor.insert('l');
95
+ * editor.insert('o');
96
+ * console.log(editor.getText()); // 'Hello' // Output: "Hello"
97
+ *
98
+ * editor.delete();
99
+ * console.log(editor.getText()); // 'Hell' // Output: "Hell"
100
+ *
101
+ * editor.undo();
102
+ * console.log(editor.getText()); // 'Hello' // Output: "Hello"
103
+ *
104
+ * editor.moveCursor(1);
105
+ * editor.insert('a');
106
+ * console.log(editor.getText()); // 'Haello'
41
107
  */
42
108
  export class SinglyLinkedList<E = any, R = any> extends LinearLinkedBase<E, R, SinglyLinkedListNode<E>> {
43
109
  constructor(
@@ -15,6 +15,53 @@ import { LinearBase } from '../base/linear-base';
15
15
  * 5. Data Buffering: Acting as a buffer for data packets in network communication.
16
16
  * 6. Breadth-First Search (BFS): In traversal algorithms for graphs and trees, queues store elements that are to be visited.
17
17
  * 7. Real-time Queuing: Like queuing systems in banks or supermarkets.
18
+ * @example
19
+ * // Sliding Window using Queue
20
+ * const nums = [2, 3, 4, 1, 5];
21
+ * const k = 2;
22
+ * const queue = new Queue<number>();
23
+ *
24
+ * let maxSum = 0;
25
+ * let currentSum = 0;
26
+ *
27
+ * nums.forEach((num, i) => {
28
+ * queue.push(num);
29
+ * currentSum += num;
30
+ *
31
+ * if (queue.length > k) {
32
+ * currentSum -= queue.shift()!;
33
+ * }
34
+ *
35
+ * if (queue.length === k) {
36
+ * maxSum = Math.max(maxSum, currentSum);
37
+ * }
38
+ * });
39
+ *
40
+ * console.log(maxSum); // 7
41
+ * @example
42
+ * // Breadth-First Search (BFS) using Queue
43
+ * const graph: { [key in number]: number[] } = {
44
+ * 1: [2, 3],
45
+ * 2: [4, 5],
46
+ * 3: [],
47
+ * 4: [],
48
+ * 5: []
49
+ * };
50
+ *
51
+ * const queue = new Queue<number>();
52
+ * const visited: number[] = [];
53
+ *
54
+ * queue.push(1);
55
+ *
56
+ * while (!queue.isEmpty()) {
57
+ * const node = queue.shift()!;
58
+ * if (!visited.includes(node)) {
59
+ * visited.push(node);
60
+ * graph[node].forEach(neighbor => queue.push(neighbor));
61
+ * }
62
+ * }
63
+ *
64
+ * console.log(visited); // [1, 2, 3, 4, 5]
18
65
  */
19
66
  export class Queue<E = any, R = any> extends LinearBase<E, R> {
20
67
  constructor(elements: Iterable<E> | Iterable<R> = [], options?: QueueOptions<E, R>) {
@@ -15,6 +15,127 @@ import { IterableElementBase } from '../base';
15
15
  * 4. Function Calls: In most modern programming languages, the records of function calls are managed through a stack. When a function is called, its record (including parameters, local variables, and return address) is 'pushed' into the stack. When the function returns, its record is 'popped' from the stack.
16
16
  * 5. Expression Evaluation: Used for the evaluation of arithmetic or logical expressions, especially when dealing with parenthesis matching and operator precedence.
17
17
  * 6. Backtracking Algorithms: In problems where multiple branches need to be explored but only one branch can be explored at a time, stacks can be used to save the state at each branching point.
18
+ * @example
19
+ * // Balanced Parentheses or Brackets
20
+ * type ValidCharacters = ')' | '(' | ']' | '[' | '}' | '{';
21
+ *
22
+ * const stack = new Stack<string>();
23
+ * const input: ValidCharacters[] = '[({})]'.split('') as ValidCharacters[];
24
+ * const matches: { [key in ValidCharacters]?: ValidCharacters } = { ')': '(', ']': '[', '}': '{' };
25
+ * for (const char of input) {
26
+ * if ('([{'.includes(char)) {
27
+ * stack.push(char);
28
+ * } else if (')]}'.includes(char)) {
29
+ * if (stack.pop() !== matches[char]) {
30
+ * fail('Parentheses are not balanced');
31
+ * }
32
+ * }
33
+ * }
34
+ * console.log(stack.isEmpty()); // true
35
+ * @example
36
+ * // Expression Evaluation and Conversion
37
+ * const stack = new Stack<number>();
38
+ * const expression = [5, 3, '+']; // Equivalent to 5 + 3
39
+ * expression.forEach(token => {
40
+ * if (typeof token === 'number') {
41
+ * stack.push(token);
42
+ * } else {
43
+ * const b = stack.pop()!;
44
+ * const a = stack.pop()!;
45
+ * stack.push(token === '+' ? a + b : 0); // Only handling '+' here
46
+ * }
47
+ * });
48
+ * console.log(stack.pop()); // 8
49
+ * @example
50
+ * // Depth-First Search (DFS)
51
+ * const stack = new Stack<number>();
52
+ * const graph: { [key in number]: number[] } = { 1: [2, 3], 2: [4], 3: [5], 4: [], 5: [] };
53
+ * const visited: number[] = [];
54
+ * stack.push(1);
55
+ * while (!stack.isEmpty()) {
56
+ * const node = stack.pop()!;
57
+ * if (!visited.includes(node)) {
58
+ * visited.push(node);
59
+ * graph[node].forEach(neighbor => stack.push(neighbor));
60
+ * }
61
+ * }
62
+ * console.log(visited); // [1, 3, 5, 2, 4]
63
+ * @example
64
+ * // Backtracking Algorithms
65
+ * const stack = new Stack<[number, number]>();
66
+ * const maze = [
67
+ * ['S', ' ', 'X'],
68
+ * ['X', ' ', 'X'],
69
+ * [' ', ' ', 'E']
70
+ * ];
71
+ * const start: [number, number] = [0, 0];
72
+ * const end = [2, 2];
73
+ * const directions = [
74
+ * [0, 1], // To the right
75
+ * [1, 0], // down
76
+ * [0, -1], // left
77
+ * [-1, 0] // up
78
+ * ];
79
+ *
80
+ * const visited = new Set<string>(); // Used to record visited nodes
81
+ * stack.push(start);
82
+ * const path: number[][] = [];
83
+ *
84
+ * while (!stack.isEmpty()) {
85
+ * const [x, y] = stack.pop()!;
86
+ * if (visited.has(`${x},${y}`)) continue; // Skip already visited nodes
87
+ * visited.add(`${x},${y}`);
88
+ *
89
+ * path.push([x, y]);
90
+ *
91
+ * if (x === end[0] && y === end[1]) {
92
+ * break; // Find the end point and exit
93
+ * }
94
+ *
95
+ * for (const [dx, dy] of directions) {
96
+ * const nx = x + dx;
97
+ * const ny = y + dy;
98
+ * if (
99
+ * maze[nx]?.[ny] === ' ' || // feasible path
100
+ * maze[nx]?.[ny] === 'E' // destination
101
+ * ) {
102
+ * stack.push([nx, ny]);
103
+ * }
104
+ * }
105
+ * }
106
+ *
107
+ * expect(path).toContainEqual(end);
108
+ * @example
109
+ * // Function Call Stack
110
+ * const functionStack = new Stack<string>();
111
+ * functionStack.push('main');
112
+ * functionStack.push('foo');
113
+ * functionStack.push('bar');
114
+ * console.log(functionStack.pop()); // 'bar'
115
+ * console.log(functionStack.pop()); // 'foo'
116
+ * console.log(functionStack.pop()); // 'main'
117
+ * @example
118
+ * // Simplify File Paths
119
+ * const stack = new Stack<string>();
120
+ * const path = '/a/./b/../../c';
121
+ * path.split('/').forEach(segment => {
122
+ * if (segment === '..') stack.pop();
123
+ * else if (segment && segment !== '.') stack.push(segment);
124
+ * });
125
+ * console.log(stack.elements.join('/')); // 'c'
126
+ * @example
127
+ * // Stock Span Problem
128
+ * const stack = new Stack<number>();
129
+ * const prices = [100, 80, 60, 70, 60, 75, 85];
130
+ * const spans: number[] = [];
131
+ * prices.forEach((price, i) => {
132
+ * while (!stack.isEmpty() && prices[stack.peek()!] <= price) {
133
+ * stack.pop();
134
+ * }
135
+ * spans.push(stack.isEmpty() ? i + 1 : i - stack.peek()!);
136
+ * stack.push(i);
137
+ * });
138
+ * console.log(spans); // [1, 1, 1, 2, 1, 4, 6]
18
139
  */
19
140
  export class Stack<E = any, R = any> extends IterableElementBase<E, R> {
20
141
  constructor(elements: Iterable<E> | Iterable<R> = [], options?: StackOptions<E, R>) {
@@ -1,9 +1,4 @@
1
- export type ToThunkFn<R = any> = () => R;
2
- export type Thunk<R = any> = ToThunkFn<R> & { __THUNK__?: symbol };
3
- export type TrlFn<A extends any[] = any[], R = any> = (...args: A) => R;
4
- export type TrlAsyncFn = (...args: any[]) => any;
5
-
6
- export type SpecifyOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
1
+ export type Thunk<T> = () => T | Thunk<T>;
7
2
 
8
3
  export type Any = string | number | bigint | boolean | symbol | undefined | object;
9
4
 
@@ -5,7 +5,7 @@
5
5
  * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
6
6
  * @license MIT License
7
7
  */
8
- import type { Comparable, ComparablePrimitive, Thunk, ToThunkFn, TrlAsyncFn, TrlFn } from '../types';
8
+ import type { Comparable, ComparablePrimitive, Thunk } from '../types';
9
9
 
10
10
  /**
11
11
  * The function generates a random UUID (Universally Unique Identifier) in TypeScript.
@@ -47,90 +47,18 @@ export const arrayRemove = function <T>(array: T[], predicate: (item: T, index:
47
47
  return result;
48
48
  };
49
49
 
50
- export const THUNK_SYMBOL = Symbol('thunk');
51
50
 
52
- /**
53
- * The function `isThunk` checks if a given value is a function with a specific symbol property.
54
- * @param {any} fnOrValue - The `fnOrValue` parameter in the `isThunk` function can be either a
55
- * function or a value that you want to check if it is a thunk. Thunks are functions that are wrapped
56
- * around a value or computation for lazy evaluation. The function checks if the `fnOrValue` is
57
- * @returns The function `isThunk` is checking if the input `fnOrValue` is a function and if it has a
58
- * property `__THUNK__` equal to `THUNK_SYMBOL`. The return value will be `true` if both conditions are
59
- * met, otherwise it will be `false`.
60
- */
61
- export const isThunk = (fnOrValue: any) => {
62
- return typeof fnOrValue === 'function' && fnOrValue.__THUNK__ === THUNK_SYMBOL;
63
- };
64
-
65
- /**
66
- * The `toThunk` function in TypeScript converts a function into a thunk by wrapping it in a closure.
67
- * @param {ToThunkFn} fn - `fn` is a function that will be converted into a thunk.
68
- * @returns A thunk function is being returned. Thunk functions are functions that delay the evaluation
69
- * of an expression or operation until it is explicitly called or invoked. In this case, the `toThunk`
70
- * function takes a function `fn` as an argument and returns a thunk function that, when called, will
71
- * execute the `fn` function provided as an argument.
72
- */
73
- export const toThunk = (fn: ToThunkFn): Thunk => {
74
- const thunk = () => fn();
75
- thunk.__THUNK__ = THUNK_SYMBOL;
76
- return thunk;
77
- };
78
-
79
- /**
80
- * The `trampoline` function in TypeScript enables tail call optimization by using thunks to avoid
81
- * stack overflow.
82
- * @param {TrlFn} fn - The `fn` parameter in the `trampoline` function is a function that takes any
83
- * number of arguments and returns a value.
84
- * @returns The `trampoline` function returns an object with two properties:
85
- * 1. A function that executes the provided function `fn` and continues to execute any thunks returned
86
- * by `fn` until a non-thunk value is returned.
87
- * 2. A `cont` property that is a function which creates a thunk for the provided function `fn`.
88
- */
89
- export const trampoline = (fn: TrlFn) => {
90
- const cont = (...args: [...Parameters<TrlFn>]): ReturnType<TrlFn> => toThunk(() => fn(...args));
91
-
92
- return Object.assign(
93
- (...args: [...Parameters<TrlFn>]) => {
94
- let result = fn(...args);
95
-
96
- while (isThunk(result) && typeof result === 'function') {
97
- result = result();
98
- }
99
-
100
- return result;
101
- },
102
- { cont }
103
- );
104
- };
105
-
106
- /**
107
- * The `trampolineAsync` function in TypeScript allows for asynchronous trampolining of a given
108
- * function.
109
- * @param {TrlAsyncFn} fn - The `fn` parameter in the `trampolineAsync` function is expected to be a
110
- * function that returns a Promise. This function will be called recursively until a non-thunk value is
111
- * returned.
112
- * @returns The `trampolineAsync` function returns an object with two properties:
113
- * 1. An async function that executes the provided `TrlAsyncFn` function and continues to execute any
114
- * thunks returned by the function until a non-thunk value is returned.
115
- * 2. A `cont` property that is a function which wraps the provided `TrlAsyncFn` function in a thunk
116
- * and returns it.
117
- */
118
- export const trampolineAsync = (fn: TrlAsyncFn) => {
119
- const cont = (...args: [...Parameters<TrlAsyncFn>]): ReturnType<TrlAsyncFn> => toThunk(() => fn(...args));
120
-
121
- return Object.assign(
122
- async (...args: [...Parameters<TrlAsyncFn>]) => {
123
- let result = await fn(...args);
124
-
125
- while (isThunk(result) && typeof result === 'function') {
126
- result = await result();
127
- }
51
+ export function isThunk<T>(result: T | Thunk<T>): result is Thunk<T> {
52
+ return typeof result === 'function';
53
+ }
128
54
 
129
- return result;
130
- },
131
- { cont }
132
- );
133
- };
55
+ export function trampoline<T>(thunk: Thunk<T>): T {
56
+ let result: T | Thunk<T> = thunk;
57
+ while (isThunk(result)) {
58
+ result = result();
59
+ }
60
+ return result;
61
+ }
134
62
 
135
63
  /**
136
64
  * The function `getMSB` returns the most significant bit of a given number.