diff --git a/.editorconfig b/.editorconfig
index 7396604..5fee044 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -3,12 +3,12 @@
root=true # represents the top-level EditorConfig configuration file
[*] # means applicable to all files
-charset = utf-8 #Set the file character set to utf-8
-indent_style = space #Indent style (tab | space)
+charset = utf-8 # Set the file character set to utf-8
+indent_style = space # Indent style (tab | space)
indent_size = 2 # indent size
end_of_line = lf # Control line break type (lf | cr | crlf)
trim_trailing_whitespace = true # Remove any whitespace characters at the beginning of the line
-insert_final_newline = true #Always insert a new line at the end of the file
+insert_final_newline = true # Always insert a new line at the end of the file
[*.md] # Indicates that only md files apply the following rules
max_line_length = off
diff --git a/.eslintrc.js b/.eslintrc.js
index b458a35..0953b89 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -43,8 +43,8 @@ module.exports = {
}
}
],
- "brace-style": ["error", "1tbs", {"allowSingleLine": true}],
- "object-curly-spacing": ["error", "never"]
+ // "brace-style": ["error", "1tbs", { "allowSingleLine": true }],
+ "object-curly-spacing": ["warn", "always"]
},
"settings": {
"import/parsers": {
diff --git a/.prettierrc.js b/.prettierrc.js
index 2458204..de198d7 100644
--- a/.prettierrc.js
+++ b/.prettierrc.js
@@ -1,6 +1,6 @@
module.exports = {
"arrowParens": "avoid",
- "bracketSpacing": false,
+ "bracketSpacing": true,
"htmlWhitespaceSensitivity": "css",
"insertPragma": false,
"bracketSameLine": false,
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9ea69d7..1593cfd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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.44.1](https://github.com/zrwusa/data-structure-typed/compare/v1.35.0...main) (upcoming)
+## [v1.45.0](https://github.com/zrwusa/data-structure-typed/compare/v1.35.0...main) (upcoming)
### Changes
diff --git a/README.md b/README.md
index 4800d99..1993ffe 100644
--- a/README.md
+++ b/README.md
@@ -735,49 +735,49 @@ optimal approach to data structure design.
[//]: # (No deletion!!! Start of Replace Section)
avl-tree
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 add randomly | 36.59 | 27.33 | 0.02 |
10,000 add & delete randomly | 71.18 | 14.05 | 0.00 |
10,000 addMany | 45.45 | 22.00 | 0.01 |
10,000 get | 28.08 | 35.62 | 9.19e-4 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 add randomly | 33.34 | 29.99 | 0.00 |
10,000 add & delete randomly | 72.30 | 13.83 | 0.00 |
10,000 addMany | 49.50 | 20.20 | 0.00 |
10,000 get | 27.23 | 36.73 | 7.19e-4 |
binary-tree
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000 add randomly | 12.48 | 80.10 | 3.98e-4 |
1,000 add & delete randomly | 16.91 | 59.15 | 0.00 |
1,000 addMany | 10.66 | 93.85 | 4.57e-4 |
1,000 get | 18.32 | 54.60 | 5.16e-4 |
1,000 dfs | 155.40 | 6.44 | 0.00 |
1,000 bfs | 57.64 | 17.35 | 0.01 |
1,000 morris | 296.45 | 3.37 | 0.11 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000 add randomly | 12.20 | 81.97 | 8.36e-5 |
1,000 add & delete randomly | 15.93 | 62.77 | 2.09e-4 |
1,000 addMany | 10.36 | 96.56 | 2.01e-4 |
1,000 get | 18.43 | 54.26 | 4.67e-4 |
1,000 dfs | 154.61 | 6.47 | 0.00 |
1,000 bfs | 57.73 | 17.32 | 0.01 |
1,000 morris | 258.47 | 3.87 | 0.00 |
bst
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 add randomly | 28.79 | 34.73 | 5.70e-4 |
10,000 add & delete randomly | 71.20 | 14.04 | 0.00 |
10,000 addMany | 32.45 | 30.81 | 0.01 |
10,000 get | 30.81 | 32.46 | 0.00 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 add randomly | 29.44 | 33.96 | 3.99e-4 |
10,000 add & delete randomly | 72.35 | 13.82 | 0.00 |
10,000 addMany | 29.76 | 33.60 | 0.00 |
10,000 get | 28.53 | 35.05 | 5.76e-4 |
rb-tree
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
100,000 add | 100.90 | 9.91 | 0.01 |
100,000 competitor add | 46.94 | 21.31 | 0.00 |
100,000 add & delete randomly | 226.33 | 4.42 | 0.02 |
100,000 getNode | 39.13 | 25.55 | 0.01 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
100,000 add | 90.42 | 11.06 | 0.01 |
100,000 add & delete randomly | 223.52 | 4.47 | 0.02 |
100,000 getNode | 38.67 | 25.86 | 0.00 |
directed-graph
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000 addVertex | 0.10 | 9661.78 | 7.45e-7 |
1,000 addEdge | 6.19 | 161.53 | 3.24e-4 |
1,000 getVertex | 0.05 | 2.03e+4 | 8.46e-6 |
1,000 getEdge | 24.52 | 40.78 | 0.00 |
tarjan | 218.05 | 4.59 | 0.01 |
tarjan all | 219.89 | 4.55 | 0.00 |
topologicalSort | 179.79 | 5.56 | 0.01 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000 addVertex | 0.11 | 9499.56 | 5.09e-6 |
1,000 addEdge | 6.37 | 157.04 | 8.13e-4 |
1,000 getVertex | 0.05 | 2.15e+4 | 1.20e-6 |
1,000 getEdge | 22.44 | 44.56 | 0.00 |
tarjan | 213.53 | 4.68 | 0.01 |
tarjan all | 215.75 | 4.63 | 0.00 |
topologicalSort | 175.51 | 5.70 | 0.01 |
hash-map
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 set | 0.78 | 1275.91 | 8.70e-5 |
10,000 competitor set | 0.59 | 1694.57 | 1.30e-5 |
10,000 set & get | 1.04 | 960.33 | 2.28e-5 |
10,000 competitor set & get | 0.68 | 1474.34 | 1.08e-5 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 set | 0.76 | 1308.63 | 1.65e-5 |
10,000 set & get | 1.03 | 966.59 | 2.21e-5 |
heap
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 add & pop | 4.63 | 215.97 | 6.56e-5 |
10,000 fib add & pop | 358.14 | 2.79 | 0.00 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 add & pop | 4.65 | 214.92 | 1.18e-4 |
10,000 fib add & pop | 367.35 | 2.72 | 0.01 |
doubly-linked-list
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000,000 unshift | 212.23 | 4.71 | 0.03 |
1,000,000 competitor unshift | 78.93 | 12.67 | 0.02 |
1,000,000 unshift & shift | 166.32 | 6.01 | 0.01 |
1,000,000 insertBefore | 332.92 | 3.00 | 0.04 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000,000 unshift | 222.80 | 4.49 | 0.06 |
1,000,000 unshift & shift | 174.60 | 5.73 | 0.04 |
1,000,000 insertBefore | 309.21 | 3.23 | 0.07 |
singly-linked-list
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 push & pop | 222.69 | 4.49 | 0.01 |
10,000 insertBefore | 250.47 | 3.99 | 0.01 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 push & pop | 214.75 | 4.66 | 0.01 |
10,000 insertBefore | 250.45 | 3.99 | 0.01 |
max-priority-queue
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 refill & poll | 11.61 | 86.12 | 2.65e-4 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 refill & poll | 11.44 | 87.43 | 1.80e-4 |
priority-queue
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 add & pop | 12.58 | 79.46 | 3.35e-4 |
10,000 competitor add & pop | 2.15 | 464.55 | 3.30e-5 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
10,000 add & pop | 12.41 | 80.57 | 1.56e-4 |
deque
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000,000 push | 206.22 | 4.85 | 0.04 |
1,000,000 competitor push | 22.29 | 44.87 | 0.00 |
1,000,000 shift | 26.65 | 37.52 | 0.00 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000,000 push | 219.15 | 4.56 | 0.04 |
1,000,000 shift | 26.76 | 37.37 | 0.00 |
queue
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000,000 push | 46.76 | 21.39 | 0.02 |
1,000,000 competitor push | 48.74 | 20.52 | 0.01 |
1,000,000 push & shift | 80.87 | 12.36 | 0.00 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000,000 push | 45.17 | 22.14 | 0.01 |
1,000,000 push & shift | 80.41 | 12.44 | 0.00 |
stack
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000,000 push | 43.03 | 23.24 | 0.01 |
1,000,000 competitor push | 72.29 | 13.83 | 0.05 |
1,000,000 push & pop | 49.55 | 20.18 | 0.01 |
1,000,000 competitor push & pop | 51.10 | 19.57 | 0.01 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
1,000,000 push | 43.67 | 22.90 | 0.01 |
1,000,000 push & pop | 48.18 | 20.76 | 0.00 |
trie
-
test name | time taken (ms) | executions per sec | sample deviation |
---|
100,000 push | 57.67 | 17.34 | 0.03 |
100,000 getWords | 118.82 | 8.42 | 0.02 |
+
test name | time taken (ms) | executions per sec | sample deviation |
---|
100,000 push | 60.46 | 16.54 | 0.00 |
100,000 getWords | 83.13 | 12.03 | 0.00 |
[//]: # (No deletion!!! End of Replace Section)
\ No newline at end of file
diff --git a/package.json b/package.json
index f55a664..2c3bacf 100644
--- a/package.json
+++ b/package.json
@@ -32,7 +32,7 @@
"format:src": "prettier --write 'src/**/*.{js,ts}'",
"format:test": "prettier --write 'test/**/*.{js,ts}'",
"format": "npm run format:src && npm run format:test",
- "ci": "env && git fetch --tags && npm run check && npm run lint && npm run build && npm run test:unit && npm run changelog",
+ "ci": "env && git fetch --tags && 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",
diff --git a/src/data-structures/binary-tree/avl-tree.ts b/src/data-structures/binary-tree/avl-tree.ts
index c21eafa..04ce1b1 100644
--- a/src/data-structures/binary-tree/avl-tree.ts
+++ b/src/data-structures/binary-tree/avl-tree.ts
@@ -5,10 +5,10 @@
* @copyright Copyright (c) 2022 Tyler Zeng
* @license MIT License
*/
-import {BST, BSTNode} from './bst';
-import type {AVLTreeNodeNested, AVLTreeOptions, BiTreeDeleteResult, BTNKey} from '../../types';
-import {BTNCallback} from '../../types';
-import {IBinaryTree} from '../../interfaces';
+import { BST, BSTNode } from './bst';
+import type { AVLTreeNodeNested, AVLTreeOptions, BiTreeDeleteResult, BTNKey } from '../../types';
+import { BTNCallback } from '../../types';
+import { IBinaryTree } from '../../interfaces';
export class AVLTreeNode = AVLTreeNodeNested> extends BSTNode {
height: number;
@@ -21,7 +21,8 @@ export class AVLTreeNode = AVLTreeNodeNeste
export class AVLTree = AVLTreeNode>>
extends BST
- implements IBinaryTree {
+ implements IBinaryTree
+{
/**
* This is a constructor function for an AVL tree data structure in TypeScript.
* @param {AVLTreeOptions} [options] - The `options` parameter is an optional object that can be passed to the
@@ -95,7 +96,7 @@ export class AVLTree = AVLTreeNode[] {
if ((identifier as any) instanceof AVLTreeNode) callback = (node => node) as C;
const deletedResults = super.delete(identifier, callback);
- for (const {needBalanced} of deletedResults) {
+ for (const { needBalanced } of deletedResults) {
if (needBalanced) {
this._balancePath(needBalanced);
}
@@ -118,7 +119,7 @@ export class AVLTree = AVLTreeNode
* @license MIT License
*/
-import {getMSB} from '../../utils';
+import { getMSB } from '../../utils';
export class BinaryIndexedTree {
protected readonly _freq: number;
@@ -17,10 +17,10 @@ export class BinaryIndexedTree {
* @param - - `frequency`: The default frequency value. It is optional and has a default
* value of 0.
*/
- constructor({frequency = 0, max}: {frequency?: number; max: number}) {
+ constructor({ frequency = 0, max }: { frequency?: number; max: number }) {
this._freq = frequency;
this._max = max;
- this._freqMap = {0: 0};
+ this._freqMap = { 0: 0 };
this._msb = getMSB(max);
this._negativeCount = frequency < 0 ? max : 0;
}
diff --git a/src/data-structures/binary-tree/binary-tree.ts b/src/data-structures/binary-tree/binary-tree.ts
index bd1c106..46af143 100644
--- a/src/data-structures/binary-tree/binary-tree.ts
+++ b/src/data-structures/binary-tree/binary-tree.ts
@@ -6,11 +6,11 @@
* @license MIT License
*/
-import type {BinaryTreeNodeNested, BinaryTreeOptions, BTNCallback, BTNKey} from '../../types';
-import {BiTreeDeleteResult, DFSOrderPattern, FamilyPosition, IterationType} from '../../types';
-import {IBinaryTree} from '../../interfaces';
-import {trampoline} from '../../utils';
-import {Queue} from '../queue';
+import type { BinaryTreeNodeNested, BinaryTreeOptions, BTNCallback, BTNKey } from '../../types';
+import { BiTreeDeleteResult, DFSOrderPattern, FamilyPosition, IterationType } from '../../types';
+import { IBinaryTree } from '../../interfaces';
+import { trampoline } from '../../utils';
+import { Queue } from '../queue';
/**
* Represents a node in a binary tree.
@@ -107,7 +107,9 @@ export class BinaryTreeNode = BinaryTree
* Represents a binary tree data structure.
* @template N - The type of the binary tree's nodes.
*/
-export class BinaryTree = BinaryTreeNode>> implements IBinaryTree {
+export class BinaryTree = BinaryTreeNode>>
+ implements IBinaryTree
+{
iterationType: IterationType = IterationType.ITERATIVE;
/**
@@ -116,7 +118,7 @@ export class BinaryTree = BinaryTreeNode
*/
constructor(options?: BinaryTreeOptions) {
if (options) {
- const {iterationType = IterationType.ITERATIVE} = options;
+ const { iterationType = IterationType.ITERATIVE } = options;
this.iterationType = iterationType;
}
this._size = 0;
@@ -315,7 +317,7 @@ export class BinaryTree = BinaryTreeNode
// Handle the case when there's only one root node
this._setRoot(null);
} else {
- const {familyPosition: fp} = curr;
+ const { familyPosition: fp } = curr;
if (fp === FamilyPosition.LEFT || fp === FamilyPosition.ROOT_LEFT) {
parent.left = curr.right;
} else if (fp === FamilyPosition.RIGHT || fp === FamilyPosition.ROOT_RIGHT) {
@@ -330,7 +332,8 @@ export class BinaryTree = BinaryTreeNode
const parentOfLeftSubTreeMax = leftSubTreeRightMost.parent;
orgCurrent = this._swap(curr, leftSubTreeRightMost);
if (parentOfLeftSubTreeMax) {
- if (parentOfLeftSubTreeMax.right === leftSubTreeRightMost) parentOfLeftSubTreeMax.right = leftSubTreeRightMost.left;
+ if (parentOfLeftSubTreeMax.right === leftSubTreeRightMost)
+ parentOfLeftSubTreeMax.right = leftSubTreeRightMost.left;
else parentOfLeftSubTreeMax.left = leftSubTreeRightMost.left;
needBalanced = parentOfLeftSubTreeMax;
}
@@ -339,7 +342,7 @@ export class BinaryTree = BinaryTreeNode
}
this._size = this.size - 1;
- deletedResult.push({deleted: orgCurrent, needBalanced});
+ deletedResult.push({ deleted: orgCurrent, needBalanced });
return deletedResult;
}
@@ -409,14 +412,14 @@ export class BinaryTree = BinaryTreeNode
return _getMaxHeight(beginRoot);
} else {
- const stack: {node: N; depth: number}[] = [{node: beginRoot, depth: 0}];
+ const stack: { node: N; depth: number }[] = [{ node: beginRoot, depth: 0 }];
let maxHeight = 0;
while (stack.length > 0) {
- const {node, depth} = stack.pop()!;
+ const { node, depth } = stack.pop()!;
- if (node.left) stack.push({node: node.left, depth: depth + 1});
- if (node.right) stack.push({node: node.right, depth: depth + 1});
+ if (node.left) stack.push({ node: node.left, depth: depth + 1 });
+ if (node.right) stack.push({ node: node.right, depth: depth + 1 });
maxHeight = Math.max(maxHeight, depth);
}
@@ -912,7 +915,10 @@ export class BinaryTree = BinaryTreeNode
* @returns The function `getLeftMost` returns the leftmost node (`N`) in the binary tree. If there
* is no leftmost node, it returns `null` or `undefined` depending on the input.
*/
- getLeftMost(beginRoot: BTNKey | N | null | undefined = this.root, iterationType = this.iterationType): N | null | undefined {
+ getLeftMost(
+ beginRoot: BTNKey | N | null | undefined = this.root,
+ iterationType = this.iterationType
+ ): N | null | undefined {
beginRoot = this.ensureNotKey(beginRoot);
if (!beginRoot) return beginRoot;
@@ -955,7 +961,10 @@ export class BinaryTree = BinaryTreeNode
* @returns The function `getRightMost` returns the rightmost node (`N`) in a binary tree. If there
* is no rightmost node, it returns `null` or `undefined`, depending on the input.
*/
- getRightMost(beginRoot: BTNKey | N | null | undefined = this.root, iterationType = this.iterationType): N | null | undefined {
+ getRightMost(
+ beginRoot: BTNKey | N | null | undefined = this.root,
+ iterationType = this.iterationType
+ ): N | null | undefined {
// TODO support get right most by passing key in
beginRoot = this.ensureNotKey(beginRoot);
if (!beginRoot) return beginRoot;
@@ -1284,7 +1293,7 @@ export class BinaryTree = BinaryTreeNode
_traverse(beginRoot);
} else {
// 0: visit, 1: print
- const stack: {opt: 0 | 1; node: N | null | undefined}[] = [{opt: 0, node: beginRoot}];
+ const stack: { opt: 0 | 1; node: N | null | undefined }[] = [{ opt: 0, node: beginRoot }];
while (stack.length > 0) {
const cur = stack.pop();
@@ -1299,24 +1308,24 @@ export class BinaryTree = BinaryTreeNode
} else {
switch (pattern) {
case 'in':
- cur.node && stack.push({opt: 0, node: cur.node.right});
- stack.push({opt: 1, node: cur.node});
- cur.node && stack.push({opt: 0, node: cur.node.left});
+ cur.node && stack.push({ opt: 0, node: cur.node.right });
+ stack.push({ opt: 1, node: cur.node });
+ cur.node && stack.push({ opt: 0, node: cur.node.left });
break;
case 'pre':
- cur.node && stack.push({opt: 0, node: cur.node.right});
- cur.node && stack.push({opt: 0, node: cur.node.left});
- stack.push({opt: 1, node: cur.node});
+ cur.node && stack.push({ opt: 0, node: cur.node.right });
+ cur.node && stack.push({ opt: 0, node: cur.node.left });
+ stack.push({ opt: 1, node: cur.node });
break;
case 'post':
- stack.push({opt: 1, node: cur.node});
- cur.node && stack.push({opt: 0, node: cur.node.right});
- cur.node && stack.push({opt: 0, node: cur.node.left});
+ stack.push({ opt: 1, node: cur.node });
+ cur.node && stack.push({ opt: 0, node: cur.node.right });
+ cur.node && stack.push({ opt: 0, node: cur.node.left });
break;
default:
- cur.node && stack.push({opt: 0, node: cur.node.right});
- stack.push({opt: 1, node: cur.node});
- cur.node && stack.push({opt: 0, node: cur.node.left});
+ cur.node && stack.push({ opt: 0, node: cur.node.right });
+ stack.push({ opt: 1, node: cur.node });
+ cur.node && stack.push({ opt: 0, node: cur.node.left });
break;
}
}
@@ -1798,7 +1807,7 @@ export class BinaryTree = BinaryTreeNode
destNode = this.ensureNotKey(destNode);
if (srcNode && destNode) {
- const {key, value} = destNode;
+ const { key, value } = destNode;
const tempNode = this.createNode(key, value);
if (tempNode) {
diff --git a/src/data-structures/binary-tree/bst.ts b/src/data-structures/binary-tree/bst.ts
index 67ca09a..d2f1d86 100644
--- a/src/data-structures/binary-tree/bst.ts
+++ b/src/data-structures/binary-tree/bst.ts
@@ -5,11 +5,11 @@
* @copyright Copyright (c) 2022 Tyler Zeng
* @license MIT License
*/
-import type {BSTComparator, BSTNodeNested, BSTOptions, BTNCallback, BTNKey} from '../../types';
-import {CP, IterationType} from '../../types';
-import {BinaryTree, BinaryTreeNode} from './binary-tree';
-import {IBinaryTree} from '../../interfaces';
-import {Queue} from '../queue';
+import type { BSTComparator, BSTNodeNested, BSTOptions, BTNCallback, BTNKey } from '../../types';
+import { CP, IterationType } from '../../types';
+import { BinaryTree, BinaryTreeNode } from './binary-tree';
+import { IBinaryTree } from '../../interfaces';
+import { Queue } from '../queue';
export class BSTNode = BSTNodeNested> extends BinaryTreeNode {
override parent?: N;
@@ -62,7 +62,10 @@ export class BSTNode = BSTNodeNested> extend
}
}
-export class BST = BSTNode>> extends BinaryTree implements IBinaryTree {
+export class BST = BSTNode>>
+ extends BinaryTree
+ implements IBinaryTree
+{
/**
* The constructor function initializes a binary search tree with an optional comparator function.
* @param {BSTOptions} [options] - An optional object that contains additional configuration options
@@ -72,7 +75,7 @@ export class BST = BSTNode>
super(options);
this._root = undefined;
if (options !== undefined) {
- const {comparator} = options;
+ const { comparator } = options;
if (comparator !== undefined) {
this._comparator = comparator;
}
@@ -225,7 +228,9 @@ export class BST = BSTNode>
}
const inserted: (N | undefined)[] = [];
- const combinedArr: [BTNKey | N, V][] = keysOrNodes.map((value: BTNKey | N, index) => [value, data?.[index]] as [BTNKey | N, V]);
+ const combinedArr: [BTNKey | N, V][] = keysOrNodes.map(
+ (value: BTNKey | N, index) => [value, data?.[index]] as [BTNKey | N, V]
+ );
let sorted = [];
diff --git a/src/data-structures/binary-tree/rb-tree.ts b/src/data-structures/binary-tree/rb-tree.ts
index 9c95297..788a7f5 100644
--- a/src/data-structures/binary-tree/rb-tree.ts
+++ b/src/data-structures/binary-tree/rb-tree.ts
@@ -6,12 +6,23 @@
* @license MIT License
*/
-import {BiTreeDeleteResult, BTNCallback, BTNKey, IterationType, RBTNColor, RBTreeOptions, RedBlackTreeNodeNested} from '../../types';
-import {BST, BSTNode} from './bst';
-import {IBinaryTree} from '../../interfaces';
-import {BinaryTreeNode} from './binary-tree';
+import {
+ BiTreeDeleteResult,
+ BTNCallback,
+ BTNKey,
+ IterationType,
+ RBTNColor,
+ RBTreeOptions,
+ RedBlackTreeNodeNested
+} from '../../types';
+import { BST, BSTNode } from './bst';
+import { IBinaryTree } from '../../interfaces';
+import { BinaryTreeNode } from './binary-tree';
-export class RedBlackTreeNode = RedBlackTreeNodeNested> extends BSTNode {
+export class RedBlackTreeNode = RedBlackTreeNodeNested> extends BSTNode<
+ V,
+ N
+> {
color: RBTNColor;
constructor(key: BTNKey, value?: V, color: RBTNColor = RBTNColor.BLACK) {
@@ -29,7 +40,8 @@ export class RedBlackTreeNode = RedBla
*/
export class RedBlackTree = RedBlackTreeNode>>
extends BST
- implements IBinaryTree {
+ implements IBinaryTree
+{
NIL: N = new RedBlackTreeNode(NaN) as unknown as N;
/**
diff --git a/src/data-structures/binary-tree/segment-tree.ts b/src/data-structures/binary-tree/segment-tree.ts
index fc366e8..3768822 100644
--- a/src/data-structures/binary-tree/segment-tree.ts
+++ b/src/data-structures/binary-tree/segment-tree.ts
@@ -6,7 +6,7 @@
* @license MIT License
*/
-import type {SegmentTreeNodeVal} from '../../types';
+import type { SegmentTreeNodeVal } from '../../types';
export class SegmentTreeNode {
start = 0;
diff --git a/src/data-structures/binary-tree/tree-multimap.ts b/src/data-structures/binary-tree/tree-multimap.ts
index 06faaf4..16fa249 100644
--- a/src/data-structures/binary-tree/tree-multimap.ts
+++ b/src/data-structures/binary-tree/tree-multimap.ts
@@ -5,12 +5,15 @@
* @copyright Copyright (c) 2022 Tyler Zeng
* @license MIT License
*/
-import type {BTNKey, TreeMultimapNodeNested, TreeMultimapOptions} from '../../types';
-import {BiTreeDeleteResult, BTNCallback, CP, FamilyPosition, IterationType} from '../../types';
-import {IBinaryTree} from '../../interfaces';
-import {AVLTree, AVLTreeNode} from './avl-tree';
+import type { BTNKey, TreeMultimapNodeNested, TreeMultimapOptions } from '../../types';
+import { BiTreeDeleteResult, BTNCallback, CP, FamilyPosition, IterationType } from '../../types';
+import { IBinaryTree } from '../../interfaces';
+import { AVLTree, AVLTreeNode } from './avl-tree';
-export class TreeMultimapNode = TreeMultimapNodeNested> extends AVLTreeNode {
+export class TreeMultimapNode<
+ V = any,
+ N extends TreeMultimapNode = TreeMultimapNodeNested
+> extends AVLTreeNode {
count: number;
/**
@@ -34,7 +37,8 @@ export class TreeMultimapNode = TreeMu
*/
export class TreeMultimap = TreeMultimapNode>>
extends AVLTree
- implements IBinaryTree {
+ implements IBinaryTree
+{
/**
* The constructor function for a TreeMultimap class in TypeScript, which extends another class and sets an option to
* merge duplicated values.
@@ -292,7 +296,7 @@ export class TreeMultimap = TreeMultim
if (!parent) {
if (curr.right !== undefined) this._setRoot(curr.right);
} else {
- const {familyPosition: fp} = curr;
+ const { familyPosition: fp } = curr;
if (fp === FamilyPosition.LEFT || fp === FamilyPosition.ROOT_LEFT) {
parent.left = curr.right;
} else if (fp === FamilyPosition.RIGHT || fp === FamilyPosition.ROOT_RIGHT) {
@@ -320,7 +324,7 @@ export class TreeMultimap = TreeMultim
if (orgCurrent) this._count -= orgCurrent.count;
}
- deletedResult.push({deleted: orgCurrent, needBalanced});
+ deletedResult.push({ deleted: orgCurrent, needBalanced });
if (needBalanced) {
this._balancePath(needBalanced);
@@ -396,7 +400,7 @@ export class TreeMultimap = TreeMultim
srcNode = this.ensureNotKey(srcNode);
destNode = this.ensureNotKey(destNode);
if (srcNode && destNode) {
- const {key, value, count, height} = destNode;
+ const { key, value, count, height } = destNode;
const tempNode = this.createNode(key, value, count);
if (tempNode) {
tempNode.height = height;
diff --git a/src/data-structures/graph/abstract-graph.ts b/src/data-structures/graph/abstract-graph.ts
index 1bd23c4..e064377 100644
--- a/src/data-structures/graph/abstract-graph.ts
+++ b/src/data-structures/graph/abstract-graph.ts
@@ -5,11 +5,11 @@
* @copyright Copyright (c) 2022 Tyler Zeng
* @license MIT License
*/
-import {uuidV4} from '../../utils';
-import {PriorityQueue} from '../priority-queue';
-import type {DijkstraResult, VertexKey} from '../../types';
-import {IGraph} from '../../interfaces';
-import {Queue} from '../queue';
+import { uuidV4 } from '../../utils';
+import { PriorityQueue } from '../priority-queue';
+import type { DijkstraResult, VertexKey } from '../../types';
+import { IGraph } from '../../interfaces';
+import { Queue } from '../queue';
export abstract class AbstractVertex {
key: VertexKey;
@@ -64,7 +64,8 @@ export abstract class AbstractGraph<
E = any,
VO extends AbstractVertex = AbstractVertex,
EO extends AbstractEdge = AbstractEdge
-> implements IGraph {
+> implements IGraph
+{
protected _vertices: Map = new Map();
get vertices(): Map {
@@ -300,11 +301,11 @@ export abstract class AbstractGraph<
return [];
}
- const stack: {vertex: VO; path: VO[]}[] = [];
- stack.push({vertex: vertex1, path: [vertex1]});
+ const stack: { vertex: VO; path: VO[] }[] = [];
+ stack.push({ vertex: vertex1, path: [vertex1] });
while (stack.length > 0) {
- const {vertex, path} = stack.pop()!;
+ const { vertex, path } = stack.pop()!;
if (vertex === vertex2) {
paths.push(path);
@@ -315,7 +316,7 @@ export abstract class AbstractGraph<
for (const neighbor of neighbors) {
if (!path.includes(neighbor)) {
const newPath = [...path, neighbor];
- stack.push({vertex: neighbor, path: newPath});
+ stack.push({ vertex: neighbor, path: newPath });
}
}
}
@@ -514,7 +515,12 @@ export abstract class AbstractGraph<
* shortest paths from the source vertex to all other vertices in the graph. If `genPaths
* @returns The function `dijkstraWithoutHeap` returns an object of type `DijkstraResult`.
*/
- dijkstraWithoutHeap(src: VO | VertexKey, dest?: VO | VertexKey | null, getMinDist?: boolean, genPaths?: boolean): DijkstraResult {
+ dijkstraWithoutHeap(
+ src: VO | VertexKey,
+ dest?: VO | VertexKey | null,
+ getMinDist?: boolean,
+ genPaths?: boolean
+ ): DijkstraResult {
if (getMinDist === undefined) getMinDist = false;
if (genPaths === undefined) genPaths = false;
@@ -586,7 +592,7 @@ export abstract class AbstractGraph<
if (genPaths) {
getPaths(destVertex);
}
- return {distMap, preMap, seen, paths, minDist, minPath};
+ return { distMap, preMap, seen, paths, minDist, minPath };
}
const neighbors = this.getNeighbors(cur);
for (const neighbor of neighbors) {
@@ -620,7 +626,7 @@ export abstract class AbstractGraph<
genPaths && getPaths(minDest);
- return {distMap, preMap, seen, paths, minDist, minPath};
+ return { distMap, preMap, seen, paths, minDist, minPath };
}
/**
@@ -657,7 +663,12 @@ export abstract class AbstractGraph<
* shortest paths from the source vertex to all other vertices in the graph. If `genPaths
* @returns The function `dijkstra` returns an object of type `DijkstraResult`.
*/
- dijkstra(src: VO | VertexKey, dest?: VO | VertexKey | null, getMinDist?: boolean, genPaths?: boolean): DijkstraResult {
+ dijkstra(
+ src: VO | VertexKey,
+ dest?: VO | VertexKey | null,
+ getMinDist?: boolean,
+ genPaths?: boolean
+ ): DijkstraResult {
if (getMinDist === undefined) getMinDist = false;
if (genPaths === undefined) genPaths = false;
@@ -681,8 +692,8 @@ export abstract class AbstractGraph<
if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Infinity);
}
- const heap = new PriorityQueue<{key: number; value: VO}>({comparator: (a, b) => a.key - b.key});
- heap.add({key: 0, value: srcVertex});
+ const heap = new PriorityQueue<{ key: number; value: VO }>({ comparator: (a, b) => a.key - b.key });
+ heap.add({ key: 0, value: srcVertex });
distMap.set(srcVertex, 0);
preMap.set(srcVertex, null);
@@ -723,7 +734,7 @@ export abstract class AbstractGraph<
if (genPaths) {
getPaths(destVertex);
}
- return {distMap, preMap, seen, paths, minDist, minPath};
+ return { distMap, preMap, seen, paths, minDist, minPath };
}
const neighbors = this.getNeighbors(cur);
for (const neighbor of neighbors) {
@@ -733,7 +744,7 @@ export abstract class AbstractGraph<
const distSrcToNeighbor = distMap.get(neighbor);
if (distSrcToNeighbor) {
if (dist + weight < distSrcToNeighbor) {
- heap.add({key: dist + weight, value: neighbor});
+ heap.add({ key: dist + weight, value: neighbor });
preMap.set(neighbor, cur);
distMap.set(neighbor, dist + weight);
}
@@ -760,7 +771,7 @@ export abstract class AbstractGraph<
getPaths(minDest);
}
- return {distMap, preMap, seen, paths, minDist, minPath};
+ return { distMap, preMap, seen, paths, minDist, minPath };
}
/**
@@ -800,7 +811,7 @@ export abstract class AbstractGraph<
// TODO
let hasNegativeCycle: boolean | undefined;
if (scanNegativeCycle) hasNegativeCycle = false;
- if (!srcVertex) return {hasNegativeCycle, distMap, preMap, paths, min, minPath};
+ if (!srcVertex) return { hasNegativeCycle, distMap, preMap, paths, min, minPath };
const vertices = this._vertices;
const numOfVertices = vertices.size;
@@ -872,7 +883,7 @@ export abstract class AbstractGraph<
}
}
- return {hasNegativeCycle, distMap, preMap, paths, min, minPath};
+ return { hasNegativeCycle, distMap, preMap, paths, min, minPath };
}
/**
@@ -913,7 +924,7 @@ export abstract class AbstractGraph<
* `predecessor` property is a 2D array of vertices (or `null`) representing the predecessor vertices in the shortest
* path between vertices in the
*/
- floydWarshall(): {costs: number[][]; predecessor: (VO | null)[][]} {
+ floydWarshall(): { costs: number[][]; predecessor: (VO | null)[][] } {
const idAndVertices = [...this._vertices];
const n = idAndVertices.length;
@@ -945,7 +956,7 @@ export abstract class AbstractGraph<
}
}
}
- return {costs, predecessor};
+ return { costs, predecessor };
}
/**
@@ -982,7 +993,12 @@ export abstract class AbstractGraph<
* are arrays of vertices that form cycles within the SCCs.
* @returns The function `tarjan` returns an object with the following properties:
*/
- tarjan(needCutVertexes: boolean = false, needBridges: boolean = false, needSCCs: boolean = true, needCycles: boolean = false) {
+ tarjan(
+ needCutVertexes: boolean = false,
+ needBridges: boolean = false,
+ needSCCs: boolean = true,
+ needCycles: boolean = false
+ ) {
// !! in undirected graph we will not let child visit parent when dfs
// !! articulation point(in dfs search tree not in graph): (cur !== root && cur.has(child)) && (low(child) >= dfn(cur)) || (cur === root && cur.children() >= 2)
// !! bridge: low(child) > dfn(cur)
@@ -1081,7 +1097,7 @@ export abstract class AbstractGraph<
});
}
- return {dfnMap, lowMap, bridges, cutVertexes, SCCs, cycles};
+ return { dfnMap, lowMap, bridges, cutVertexes, SCCs, cycles };
}
/**
diff --git a/src/data-structures/graph/directed-graph.ts b/src/data-structures/graph/directed-graph.ts
index f9c02fa..f6bc9b3 100644
--- a/src/data-structures/graph/directed-graph.ts
+++ b/src/data-structures/graph/directed-graph.ts
@@ -5,10 +5,10 @@
* @copyright Copyright (c) 2022 Tyler Zeng
* @license MIT License
*/
-import {arrayRemove} from '../../utils';
-import {AbstractEdge, AbstractGraph, AbstractVertex} from './abstract-graph';
-import type {TopologicalStatus, VertexKey} from '../../types';
-import {IGraph} from '../../interfaces';
+import { arrayRemove } from '../../utils';
+import { AbstractEdge, AbstractGraph, AbstractVertex } from './abstract-graph';
+import type { TopologicalStatus, VertexKey } from '../../types';
+import { IGraph } from '../../interfaces';
export class DirectedVertex extends AbstractVertex {
/**
@@ -45,9 +45,15 @@ export class DirectedEdge extends AbstractEdge {
}
}
-export class DirectedGraph = DirectedVertex, EO extends DirectedEdge = DirectedEdge>
+export class DirectedGraph<
+ V = any,
+ E = any,
+ VO extends DirectedVertex = DirectedVertex,
+ EO extends DirectedEdge = DirectedEdge
+ >
extends AbstractGraph
- implements IGraph {
+ implements IGraph
+{
/**
* The constructor function initializes an instance of a class.
*/
diff --git a/src/data-structures/graph/map-graph.ts b/src/data-structures/graph/map-graph.ts
index a2fc395..5707f4f 100644
--- a/src/data-structures/graph/map-graph.ts
+++ b/src/data-structures/graph/map-graph.ts
@@ -1,5 +1,5 @@
-import {MapGraphCoordinate, VertexKey} from '../../types';
-import {DirectedEdge, DirectedGraph, DirectedVertex} from './directed-graph';
+import { MapGraphCoordinate, VertexKey } from '../../types';
+import { DirectedEdge, DirectedGraph, DirectedVertex } from './directed-graph';
export class MapVertex extends DirectedVertex {
lat: number;
@@ -40,12 +40,12 @@ export class MapEdge extends DirectedEdge {
}
}
-export class MapGraph = MapVertex, EO extends MapEdge = MapEdge> extends DirectedGraph<
- V,
- E,
- VO,
- EO
-> {
+export class MapGraph<
+ V = any,
+ E = any,
+ VO extends MapVertex = MapVertex,
+ EO extends MapEdge = MapEdge
+> extends DirectedGraph {
/**
* The constructor function initializes the origin and bottomRight properties of a MapGraphCoordinate object.
* @param {MapGraphCoordinate} origin - The `origin` parameter is a `MapGraphCoordinate` object that represents the
diff --git a/src/data-structures/graph/undirected-graph.ts b/src/data-structures/graph/undirected-graph.ts
index 0d7988b..2e7fded 100644
--- a/src/data-structures/graph/undirected-graph.ts
+++ b/src/data-structures/graph/undirected-graph.ts
@@ -5,10 +5,10 @@
* @copyright Copyright (c) 2022 Tyler Zeng
* @license MIT License
*/
-import {arrayRemove} from '../../utils';
-import {AbstractEdge, AbstractGraph, AbstractVertex} from './abstract-graph';
-import type {VertexKey} from '../../types';
-import {IGraph} from '../../interfaces';
+import { arrayRemove } from '../../utils';
+import { AbstractEdge, AbstractGraph, AbstractVertex } from './abstract-graph';
+import type { VertexKey } from '../../types';
+import { IGraph } from '../../interfaces';
export class UndirectedVertex extends AbstractVertex {
/**
@@ -49,7 +49,8 @@ export class UndirectedGraph<
EO extends UndirectedEdge = UndirectedEdge
>
extends AbstractGraph
- implements IGraph {
+ implements IGraph
+{
/**
* The constructor initializes a new Map object to store edges.
*/
diff --git a/src/data-structures/hash/hash-map.ts b/src/data-structures/hash/hash-map.ts
index 247baac..0720cc1 100644
--- a/src/data-structures/hash/hash-map.ts
+++ b/src/data-structures/hash/hash-map.ts
@@ -6,19 +6,18 @@
* @license MIT License
*/
-import {isObjOrFunc, rangeCheck, throwRangeError} from "../../utils";
-import {HashMapLinkedNode, HashMapOptions, IterateDirection} from "../../types";
+import { isObjOrFunc, rangeCheck, throwRangeError } from '../../utils';
+import { HashMapLinkedNode, HashMapOptions, IterateDirection } from '../../types';
/**
* Because the implementation of HashMap relies on JavaScript's built-in objects and arrays,
* these underlying structures have already dealt with dynamic expansion and hash collisions.
* Therefore, there is no need for additional logic to handle these issues.
*/
-class HashMapIterator {
+export class HashMapIterator {
readonly hashMap: HashMap;
-
- protected _node: HashMapLinkedNode;
readonly iterateDirection: IterateDirection;
+ protected _node: HashMapLinkedNode;
protected readonly _sentinel: HashMapLinkedNode;
/**
@@ -36,13 +35,16 @@ class HashMapIterator {
* @returns The constructor does not return anything. It is used to initialize the properties and
* methods of the object being created.
*/
- constructor(node: HashMapLinkedNode, sentinel: HashMapLinkedNode,
- hashMap: HashMap, iterateDirection: IterateDirection = IterateDirection.DEFAULT) {
+ constructor(
+ node: HashMapLinkedNode,
+ sentinel: HashMapLinkedNode,
+ hashMap: HashMap,
+ iterateDirection: IterateDirection = IterateDirection.DEFAULT
+ ) {
this._node = node;
this._sentinel = sentinel;
this.iterateDirection = iterateDirection;
-
if (this.iterateDirection === IterateDirection.DEFAULT) {
this.prev = function () {
if (this._node.prev === this._sentinel) {
@@ -87,7 +89,7 @@ class HashMapIterator {
throwRangeError();
}
- return new Proxy(<[K, V]>[], {
+ return new Proxy(<[K, V]>([]), {
get: (target, prop: '0' | '1') => {
if (prop === '0') return this._node.key;
else if (prop === '1') return this._node.value;
@@ -113,7 +115,6 @@ class HashMapIterator {
return this._node !== this._sentinel;
}
-
prev() {
return this;
}
@@ -124,18 +125,12 @@ class HashMapIterator {
}
export class HashMap {
+ readonly OBJ_KEY_INDEX = Symbol('OBJ_KEY_INDEX');
protected _nodes: HashMapLinkedNode[] = [];
protected _orgMap: Record> = {};
protected _head: HashMapLinkedNode;
protected _tail: HashMapLinkedNode;
protected readonly _sentinel: HashMapLinkedNode;
- readonly OBJ_KEY_INDEX = Symbol('OBJ_KEY_INDEX');
-
- protected _size = 0;
-
- get size() {
- return this._size;
- }
/**
* The constructor initializes a HashMap object with an optional initial set of key-value pairs.
@@ -151,217 +146,14 @@ export class HashMap {
hashMap.forEach(el => {
this.set(el[0], el[1]);
});
-
}
- /**
- * Time Complexity: O(1)
- * Space Complexity: O(1)
- *
- * The `set` function adds a new key-value pair to a data structure, either using an object key or a
- * string key.
- * @param {K} key - The `key` parameter is the key to be set in the data structure. It can be of any
- * type, but typically it is a string or symbol.
- * @param {V} [value] - The `value` parameter is an optional parameter of type `V`. It represents the
- * value associated with the key being set in the data structure.
- * @param {boolean} isObjectKey - A boolean flag indicating whether the key is an object key or not.
- * @returns the size of the data structure after the key-value pair has been set.
- */
- set(key: K, value?: V, isObjectKey: boolean = isObjOrFunc(key)) {
- let newTail;
- if (isObjectKey) {
- const index = (>key)[this.OBJ_KEY_INDEX];
- if (index !== undefined) {
- this._nodes[index].value = value;
- return this._size;
- }
- Object.defineProperty(key, this.OBJ_KEY_INDEX, {
- value: this._nodes.length,
- configurable: true
- });
- newTail = {
- key: key,
- value: value,
- prev: this._tail,
- next: this._sentinel
- };
- this._nodes.push(newTail);
- } else {
- const node = this._orgMap[key];
- if (node) {
- node.value = value;
- return this._size;
- }
- this._orgMap[key] = newTail = {
- key: key,
- value: value,
- prev: this._tail,
- next: this._sentinel
- };
- }
- if (this._size === 0) {
- this._head = newTail;
- this._sentinel.next = newTail;
- } else {
- this._tail.next = newTail;
- }
- this._tail = newTail;
- this._sentinel.prev = newTail;
- return ++this._size;
- }
+ protected _size = 0;
- /**
- * Time Complexity: O(1)
- * Space Complexity: O(1)
- *
- * The function `get` retrieves the value associated with a given key from a map, either by using the
- * key directly or by using an index stored in the key object.
- * @param {K} key - The `key` parameter is the key used to retrieve a value from the map. It can be
- * of any type, but typically it is a string or symbol.
- * @param {boolean} isObjectKey - The `isObjectKey` parameter is a boolean flag that indicates
- * whether the `key` parameter is an object key or not. If `isObjectKey` is `true`, it means that
- * `key` is an object key. If `isObjectKey` is `false`, it means that `key`
- * @returns The value associated with the given key is being returned. If the key is an object key,
- * the value is retrieved from the `_nodes` array using the index stored in the `OBJ_KEY_INDEX`
- * property of the key. If the key is a string key, the value is retrieved from the `_orgMap` object
- * using the key itself. If the key is not found, `undefined` is
- */
- get(key: K, isObjectKey: boolean = isObjOrFunc(key)) {
- if (isObjectKey) {
- const index = (>key)[this.OBJ_KEY_INDEX];
- return index !== undefined ? this._nodes[index].value : undefined;
- }
- const node = this._orgMap[key];
- return node ? node.value : undefined;
- }
-
- /**
- * Time Complexity: O(n), where n is the index.
- * Space Complexity: O(1)
- *
- * The function `getAt` retrieves the key-value pair at a specified index in a linked list.
- * @param {number} index - The index parameter is a number that represents the position of the
- * element we want to retrieve from the data structure.
- * @returns The method `getAt(index: number)` is returning an array containing the key-value pair at
- * the specified index in the data structure. The key-value pair is represented as a tuple `[K, V]`,
- * where `K` is the key and `V` is the value.
- */
- getAt(index: number) {
- rangeCheck(index, 0, this._size - 1);
- let node = this._head;
- while (index--) {
- node = node.next;
- }
- return <[K, V]>[node.key, node.value];
- }
-
- /**
- * Time Complexity: O(1)
- * Space Complexity: O(1)
- *
- * The function `getIterator` returns a new instance of `HashMapIterator` based on the provided key
- * and whether it is an object key or not.
- * @param {K} key - The `key` parameter is the key used to retrieve the iterator from the HashMap. It
- * can be of any type, depending on how the HashMap is implemented.
- * @param {boolean} [isObjectKey] - The `isObjectKey` parameter is an optional boolean parameter that
- * indicates whether the `key` parameter is an object key. If `isObjectKey` is `true`, it means that
- * the `key` parameter is an object and needs to be handled differently. If `isObjectKey` is `false`
- * @returns a new instance of the `HashMapIterator` class.
- */
- getIterator(key: K, isObjectKey?: boolean) {
- let node: HashMapLinkedNode
- if (isObjectKey) {
- const index = (>key)[this.OBJ_KEY_INDEX];
- if (index === undefined) {
- node = this._sentinel
- } else {
- node = this._nodes[index];
- }
- } else {
- node = this._orgMap[key] || this._sentinel;
- }
- return new HashMapIterator(node, this._sentinel, this);
- }
-
- /**
- * Time Complexity: O(1)
- * Space Complexity: O(1)
- *
- * The `delete` function removes a key-value pair from a map-like data structure.
- * @param {K} key - The `key` parameter is the key that you want to delete from the data structure.
- * It can be of any type, but typically it is a string or an object.
- * @param {boolean} isObjectKey - The `isObjectKey` parameter is a boolean flag that indicates
- * whether the `key` parameter is an object key or not. If `isObjectKey` is `true`, it means that the
- * `key` parameter is an object key. If `isObjectKey` is `false`, it means that the
- * @returns a boolean value. It returns `true` if the deletion was successful, and `false` if the key
- * was not found.
- */
- delete(key: K, isObjectKey: boolean = isObjOrFunc(key)) {
- let node;
- if (isObjectKey) {
- const index = (>key)[this.OBJ_KEY_INDEX];
- if (index === undefined) return false;
- delete (>key)[this.OBJ_KEY_INDEX];
- node = this._nodes[index];
- delete this._nodes[index];
- } else {
- node = this._orgMap[key];
- if (node === undefined) return false;
- delete this._orgMap[key];
- }
- this._deleteNode(node);
- return true;
- }
-
- /**
- * Time Complexity: O(n), where n is the index.
- * Space Complexity: O(1)
- *
- * The `deleteAt` function deletes a node at a specified index in a linked list.
- * @param {number} index - The index parameter represents the position at which the node should be
- * deleted in the linked list.
- * @returns The size of the list after deleting the element at the specified index.
- */
- deleteAt(index: number) {
- rangeCheck(index, 0, this._size - 1);
- let node = this._head;
- while (index--) {
- node = node.next;
- }
- this._deleteNode(node);
+ get size() {
return this._size;
}
- /**
- * Time Complexity: O(1)
- * Space Complexity: O(1)
- *
- * The function checks if a data structure is empty by comparing its size to zero.
- * @returns The method is returning a boolean value indicating whether the size of the object is 0 or
- * not.
- */
- isEmpty() {
- return this._size === 0;
- }
-
- /**
- * Time Complexity: O(1)
- * Space Complexity: O(1)
- *
- * The `clear` function clears all the elements in a data structure and resets its properties.
- */
- clear() {
- // const OBJ_KEY_INDEX = this.OBJ_KEY_INDEX;
- // this._nodes.forEach(el => {
- // delete (>el.key)[OBJ_KEY_INDEX];
- // });
- this._nodes = [];
- this._orgMap = {};
- Object.setPrototypeOf(this._orgMap, null);
- this._size = 0;
- this._head = this._tail = this._sentinel.prev = this._sentinel.next = this._sentinel;
- }
-
/**
* Time Complexity: O(1)
* Space Complexity: O(1)
@@ -435,6 +227,214 @@ export class HashMap {
return <[K, V]>[this._tail.key, this._tail.value];
}
+ /**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
+ * The `set` function adds a new key-value pair to a data structure, either using an object key or a
+ * string key.
+ * @param {K} key - The `key` parameter is the key to be set in the data structure. It can be of any
+ * type, but typically it is a string or symbol.
+ * @param {V} [value] - The `value` parameter is an optional parameter of type `V`. It represents the
+ * value associated with the key being set in the data structure.
+ * @param {boolean} isObjectKey - A boolean flag indicating whether the key is an object key or not.
+ * @returns the size of the data structure after the key-value pair has been set.
+ */
+ set(key: K, value?: V, isObjectKey: boolean = isObjOrFunc(key)) {
+ let newTail;
+ if (isObjectKey) {
+ const index = (>(key))[this.OBJ_KEY_INDEX];
+ if (index !== undefined) {
+ this._nodes[index].value = value;
+ return this._size;
+ }
+ Object.defineProperty(key, this.OBJ_KEY_INDEX, {
+ value: this._nodes.length,
+ configurable: true
+ });
+ newTail = {
+ key: key,
+ value: value,
+ prev: this._tail,
+ next: this._sentinel
+ };
+ this._nodes.push(newTail);
+ } else {
+ const node = this._orgMap[(key)];
+ if (node) {
+ node.value = value;
+ return this._size;
+ }
+ this._orgMap[(key)] = newTail = {
+ key: key,
+ value: value,
+ prev: this._tail,
+ next: this._sentinel
+ };
+ }
+ if (this._size === 0) {
+ this._head = newTail;
+ this._sentinel.next = newTail;
+ } else {
+ this._tail.next = newTail;
+ }
+ this._tail = newTail;
+ this._sentinel.prev = newTail;
+ return ++this._size;
+ }
+
+ /**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
+ * The function `get` retrieves the value associated with a given key from a map, either by using the
+ * key directly or by using an index stored in the key object.
+ * @param {K} key - The `key` parameter is the key used to retrieve a value from the map. It can be
+ * of any type, but typically it is a string or symbol.
+ * @param {boolean} isObjectKey - The `isObjectKey` parameter is a boolean flag that indicates
+ * whether the `key` parameter is an object key or not. If `isObjectKey` is `true`, it means that
+ * `key` is an object key. If `isObjectKey` is `false`, it means that `key`
+ * @returns The value associated with the given key is being returned. If the key is an object key,
+ * the value is retrieved from the `_nodes` array using the index stored in the `OBJ_KEY_INDEX`
+ * property of the key. If the key is a string key, the value is retrieved from the `_orgMap` object
+ * using the key itself. If the key is not found, `undefined` is
+ */
+ get(key: K, isObjectKey: boolean = isObjOrFunc(key)) {
+ if (isObjectKey) {
+ const index = (>(key))[this.OBJ_KEY_INDEX];
+ return index !== undefined ? this._nodes[index].value : undefined;
+ }
+ const node = this._orgMap[(key)];
+ return node ? node.value : undefined;
+ }
+
+ /**
+ * Time Complexity: O(n), where n is the index.
+ * Space Complexity: O(1)
+ *
+ * The function `getAt` retrieves the key-value pair at a specified index in a linked list.
+ * @param {number} index - The index parameter is a number that represents the position of the
+ * element we want to retrieve from the data structure.
+ * @returns The method `getAt(index: number)` is returning an array containing the key-value pair at
+ * the specified index in the data structure. The key-value pair is represented as a tuple `[K, V]`,
+ * where `K` is the key and `V` is the value.
+ */
+ getAt(index: number) {
+ rangeCheck(index, 0, this._size - 1);
+ let node = this._head;
+ while (index--) {
+ node = node.next;
+ }
+ return <[K, V]>[node.key, node.value];
+ }
+
+ /**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
+ * The function `getIterator` returns a new instance of `HashMapIterator` based on the provided key
+ * and whether it is an object key or not.
+ * @param {K} key - The `key` parameter is the key used to retrieve the iterator from the HashMap. It
+ * can be of any type, depending on how the HashMap is implemented.
+ * @param {boolean} [isObjectKey] - The `isObjectKey` parameter is an optional boolean parameter that
+ * indicates whether the `key` parameter is an object key. If `isObjectKey` is `true`, it means that
+ * the `key` parameter is an object and needs to be handled differently. If `isObjectKey` is `false`
+ * @returns a new instance of the `HashMapIterator` class.
+ */
+ getIterator(key: K, isObjectKey?: boolean) {
+ let node: HashMapLinkedNode;
+ if (isObjectKey) {
+ const index = (>(key))[this.OBJ_KEY_INDEX];
+ if (index === undefined) {
+ node = this._sentinel;
+ } else {
+ node = this._nodes[index];
+ }
+ } else {
+ node = this._orgMap[(key)] || this._sentinel;
+ }
+ return new HashMapIterator(node, this._sentinel, this);
+ }
+
+ /**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
+ * The `delete` function removes a key-value pair from a map-like data structure.
+ * @param {K} key - The `key` parameter is the key that you want to delete from the data structure.
+ * It can be of any type, but typically it is a string or an object.
+ * @param {boolean} isObjectKey - The `isObjectKey` parameter is a boolean flag that indicates
+ * whether the `key` parameter is an object key or not. If `isObjectKey` is `true`, it means that the
+ * `key` parameter is an object key. If `isObjectKey` is `false`, it means that the
+ * @returns a boolean value. It returns `true` if the deletion was successful, and `false` if the key
+ * was not found.
+ */
+ delete(key: K, isObjectKey: boolean = isObjOrFunc(key)) {
+ let node;
+ if (isObjectKey) {
+ const index = (>(key))[this.OBJ_KEY_INDEX];
+ if (index === undefined) return false;
+ delete (>(key))[this.OBJ_KEY_INDEX];
+ node = this._nodes[index];
+ delete this._nodes[index];
+ } else {
+ node = this._orgMap[(key)];
+ if (node === undefined) return false;
+ delete this._orgMap[(key)];
+ }
+ this._deleteNode(node);
+ return true;
+ }
+
+ /**
+ * Time Complexity: O(n), where n is the index.
+ * Space Complexity: O(1)
+ *
+ * The `deleteAt` function deletes a node at a specified index in a linked list.
+ * @param {number} index - The index parameter represents the position at which the node should be
+ * deleted in the linked list.
+ * @returns The size of the list after deleting the element at the specified index.
+ */
+ deleteAt(index: number) {
+ rangeCheck(index, 0, this._size - 1);
+ let node = this._head;
+ while (index--) {
+ node = node.next;
+ }
+ this._deleteNode(node);
+ return this._size;
+ }
+
+ /**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
+ * The function checks if a data structure is empty by comparing its size to zero.
+ * @returns The method is returning a boolean value indicating whether the size of the object is 0 or
+ * not.
+ */
+ isEmpty() {
+ return this._size === 0;
+ }
+
+ /**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
+ * The `clear` function clears all the elements in a data structure and resets its properties.
+ */
+ clear() {
+ // const OBJ_KEY_INDEX = this.OBJ_KEY_INDEX;
+ // this._nodes.forEach(el => {
+ // delete (>el.key)[OBJ_KEY_INDEX];
+ // });
+ this._nodes = [];
+ this._orgMap = {};
+ Object.setPrototypeOf(this._orgMap, null);
+ this._size = 0;
+ this._head = this._tail = this._sentinel.prev = this._sentinel.next = this._sentinel;
+ }
+
/**
* Time Complexity: O(n), where n is the number of elements in the HashMap.
* Space Complexity: O(1)
@@ -459,7 +459,7 @@ export class HashMap {
*
* The above function is an iterator that yields key-value pairs from a linked list.
*/
- * [Symbol.iterator]() {
+ *[Symbol.iterator]() {
let node = this._head;
while (node !== this._sentinel) {
yield <[K, V]>[node.key, node.value];
@@ -478,7 +478,7 @@ export class HashMap {
* and next nodes in the list.
*/
protected _deleteNode(node: HashMapLinkedNode) {
- const {prev, next} = node;
+ const { prev, next } = node;
prev.next = next;
next.prev = prev;
if (node === this._head) {
diff --git a/src/data-structures/hash/hash-table.ts b/src/data-structures/hash/hash-table.ts
index 783819f..691bb79 100644
--- a/src/data-structures/hash/hash-table.ts
+++ b/src/data-structures/hash/hash-table.ts
@@ -18,7 +18,7 @@ export class HashTableNode {
}
}
-import {HashFunction} from '../../types';
+import { HashFunction } from '../../types';
export class HashTable {
protected static readonly DEFAULT_CAPACITY = 16;
diff --git a/src/data-structures/heap/heap.ts b/src/data-structures/heap/heap.ts
index 8544beb..5850ba7 100644
--- a/src/data-structures/heap/heap.ts
+++ b/src/data-structures/heap/heap.ts
@@ -5,10 +5,10 @@
* @license MIT License
*/
-import type {Comparator, DFSOrderPattern} from '../../types';
+import type { Comparator, DFSOrderPattern } from '../../types';
export class Heap {
- constructor(options: {comparator: Comparator; nodes?: E[]}) {
+ constructor(options: { comparator: Comparator; nodes?: E[] }) {
this._comparator = options.comparator;
if (options.nodes && options.nodes.length > 0) {
this._nodes = options.nodes;
@@ -48,7 +48,7 @@ export class Heap {
* @returns A new Heap instance.
* @param options
*/
- static heapify(options: {nodes: E[]; comparator: Comparator}): Heap {
+ static heapify(options: { nodes: E[]; comparator: Comparator }): Heap {
return new Heap(options);
}
@@ -265,7 +265,7 @@ export class Heap {
* @returns A new Heap instance containing the same elements.
*/
clone(): Heap {
- const clonedHeap = new Heap({comparator: this.comparator});
+ const clonedHeap = new Heap({ comparator: this.comparator });
clonedHeap._nodes = [...this.nodes];
return clonedHeap;
}
@@ -741,7 +741,10 @@ export class FibonacciHeap {
protected consolidate(): void {
const A: (FibonacciHeapNode | undefined)[] = new Array(this.size);
const nodes = this.consumeLinkedList(this.root);
- let x: FibonacciHeapNode | undefined, y: FibonacciHeapNode | undefined, d: number, t: FibonacciHeapNode | undefined;
+ let x: FibonacciHeapNode | undefined,
+ y: FibonacciHeapNode | undefined,
+ d: number,
+ t: FibonacciHeapNode | undefined;
for (const node of nodes) {
x = node;
diff --git a/src/data-structures/heap/max-heap.ts b/src/data-structures/heap/max-heap.ts
index be2c9b1..9b90701 100644
--- a/src/data-structures/heap/max-heap.ts
+++ b/src/data-structures/heap/max-heap.ts
@@ -6,12 +6,12 @@
* @license MIT License
*/
-import {Heap} from './heap';
-import type {Comparator} from '../../types';
+import { Heap } from './heap';
+import type { Comparator } from '../../types';
export class MaxHeap extends Heap {
constructor(
- options: {comparator: Comparator; nodes?: E[]} = {
+ options: { comparator: Comparator; nodes?: E[] } = {
comparator: (a: E, b: E) => {
if (!(typeof a === 'number' && typeof b === 'number')) {
throw new Error('The a, b params of compare function must be number');
diff --git a/src/data-structures/heap/min-heap.ts b/src/data-structures/heap/min-heap.ts
index dc86f87..e5181dd 100644
--- a/src/data-structures/heap/min-heap.ts
+++ b/src/data-structures/heap/min-heap.ts
@@ -6,12 +6,12 @@
* @license MIT License
*/
-import {Heap} from './heap';
-import type {Comparator} from '../../types';
+import { Heap } from './heap';
+import type { Comparator } from '../../types';
export class MinHeap extends Heap {
constructor(
- options: {comparator: Comparator