[core] All data structures have had their member variables access control optimized.

This commit is contained in:
Revone 2023-10-31 11:15:39 +08:00
parent 1ec5a19172
commit 8712bbd3c9
40 changed files with 179 additions and 407 deletions

View file

@ -21,8 +21,7 @@ export class AVLTreeNode<V = any, N extends AVLTreeNode<V, N> = AVLTreeNodeNeste
export class AVLTree<V = any, N extends AVLTreeNode<V, N> = AVLTreeNode<V, AVLTreeNodeNested<V>>>
extends BST<V, N>
implements IBinaryTree<V, N>
{
implements IBinaryTree<V, N> {
/**
* 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
@ -56,7 +55,6 @@ export class AVLTree<V = any, N extends AVLTreeNode<V, N> = AVLTreeNode<V, AVLTr
* @returns The method is returning the inserted node (`N`), `null`, or `undefined`.
*/
override add(keyOrNode: BTNKey | N | null, value?: V): N | null | undefined {
// TODO support node as a param
const inserted = super.add(keyOrNode, value);
if (inserted) this._balancePath(inserted);
return inserted;
@ -162,7 +160,7 @@ export class AVLTree<V = any, N extends AVLTreeNode<V, N> = AVLTreeNode<V, AVLTr
// Balance Restoration: If a balance issue is discovered after inserting a node, it requires balance restoration operations. Balance restoration includes four basic cases where rotation operations need to be performed to fix the balance:
switch (
this._balanceFactor(A) // second O(1)
) {
) {
case -2:
if (A && A.left) {
if (this._balanceFactor(A.left) <= 0) {

View file

@ -17,7 +17,7 @@ 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};
@ -31,30 +31,18 @@ export class BinaryIndexedTree {
return this._freqMap;
}
set freqMap(value: Record<number, number>) {
this._freqMap = value;
}
protected _msb: number;
get msb(): number {
return this._msb;
}
set msb(value: number) {
this._msb = value;
}
protected _negativeCount: number;
get negativeCount(): number {
return this._negativeCount;
}
set negativeCount(value: number) {
this._negativeCount = value;
}
get freq(): number {
return this._freq;
}
@ -232,9 +220,9 @@ export class BinaryIndexedTree {
*/
protected _updateNegativeCount(freqCur: number, freqNew: number): void {
if (freqCur < 0 && freqNew >= 0) {
this.negativeCount--;
this._negativeCount--;
} else if (freqCur >= 0 && freqNew < 0) {
this.negativeCount++;
this._negativeCount++;
}
}

View file

@ -43,7 +43,7 @@ export class BinaryTreeNode<V = any, N extends BinaryTreeNode<V, N> = BinaryTree
this.value = value;
}
private _left: N | null | undefined;
protected _left: N | null | undefined;
/**
* Get the left child node.
@ -63,7 +63,7 @@ export class BinaryTreeNode<V = any, N extends BinaryTreeNode<V, N> = BinaryTree
this._left = v;
}
private _right: N | null | undefined;
protected _right: N | null | undefined;
/**
* Get the right child node.
@ -108,8 +108,9 @@ export class BinaryTreeNode<V = any, N extends BinaryTreeNode<V, N> = BinaryTree
* @template N - The type of the binary tree's nodes.
*/
export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNode<V, BinaryTreeNodeNested<V>>>
implements IBinaryTree<V, N>
{
implements IBinaryTree<V, N> {
iterationType: IterationType = IterationType.ITERATIVE;
/**
* Creates a new instance of BinaryTree.
* @param {BinaryTreeOptions} [options] - The options for the binary tree.
@ -117,28 +118,11 @@ export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNode
constructor(options?: BinaryTreeOptions) {
if (options !== undefined) {
const {iterationType = IterationType.ITERATIVE} = options;
this._iterationType = iterationType;
this.iterationType = iterationType;
}
}
private _iterationType: IterationType = IterationType.ITERATIVE;
/**
* Get the iteration type used in the binary tree.
*/
get iterationType(): IterationType {
return this._iterationType;
}
/**
* Set the iteration type for the binary tree.
* @param {IterationType} v - The new iteration type to set.
*/
set iterationType(v: IterationType) {
this._iterationType = v;
}
private _root: N | null = null;
protected _root: N | null = null;
/**
* Get the root node of the binary tree.
@ -147,7 +131,7 @@ export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNode
return this._root;
}
private _size = 0;
protected _size = 0;
/**
* Get the number of nodes in the binary tree.
@ -170,7 +154,7 @@ export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNode
* Clear the binary tree, removing all nodes.
*/
clear() {
this._root = null;
this._setRoot(null);
this._size = 0;
}
@ -229,9 +213,9 @@ export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNode
} else {
this._setRoot(needInsert);
if (needInsert !== null) {
this._setSize(1);
this._size = 1;
} else {
this._setSize(0);
this._size = 0;
}
inserted = this.root;
}
@ -339,7 +323,7 @@ export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNode
}
}
}
this._setSize(this.size - 1);
this._size = this.size - 1;
bstDeletedResult.push({deleted: orgCurrent, needBalanced});
return bstDeletedResult;
@ -401,7 +385,7 @@ export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNode
return -1;
}
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) {
@ -904,7 +888,7 @@ export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = 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();
@ -1174,7 +1158,7 @@ export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNode
* @returns The `*[Symbol.iterator]` method returns a generator object that yields the keys of the
* binary tree nodes in a specific order.
*/
*[Symbol.iterator](node = this.root): Generator<BTNKey, void, undefined> {
* [Symbol.iterator](node = this.root): Generator<BTNKey, void, undefined> {
if (!node) {
return;
}
@ -1244,13 +1228,13 @@ export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNode
if (parent.left === undefined) {
parent.left = newNode;
if (newNode) {
this._setSize(this.size + 1);
this._size = this.size + 1;
}
return parent.left;
} else if (parent.right === undefined) {
parent.right = newNode;
if (newNode) {
this._setSize(this.size + 1);
this._size = this.size + 1;
}
return parent.right;
} else {
@ -1274,14 +1258,5 @@ export class BinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNode
this._root = v;
}
/**
* The function sets the value of the protected property "_size" to the given number.
* @param {number} v - The parameter "v" is a number that represents the size value that we want to
* set.
*/
protected _setSize(v: number) {
this._size = v;
}
// --- end additional methods ---
}

View file

@ -5,7 +5,7 @@
* @copyright Copyright (c) 2022 Tyler Zeng <zrwusa@gmail.com>
* @license MIT License
*/
import type {BTNKey, BSTComparator, BSTNodeNested, BSTOptions, BTNCallback} from '../../types';
import type {BSTComparator, BSTNodeNested, BSTOptions, BTNCallback, BTNKey} from '../../types';
import {CP, IterationType} from '../../types';
import {BinaryTree, BinaryTreeNode} from './binary-tree';
import {IBinaryTree} from '../../interfaces';
@ -19,8 +19,7 @@ export class BSTNode<V = any, N extends BSTNode<V, N> = BSTNodeNested<V>> extend
export class BST<V = any, N extends BSTNode<V, N> = BSTNode<V, BSTNodeNested<V>>>
extends BinaryTree<V, N>
implements IBinaryTree<V, N>
{
implements IBinaryTree<V, N> {
/**
* The constructor function initializes a binary search tree object with an optional comparator
* function.
@ -72,7 +71,7 @@ export class BST<V = any, N extends BSTNode<V, N> = BSTNode<V, BSTNodeNested<V>>
}
if (this.root === null) {
this._setRoot(newNode);
this._setSize(this.size + 1);
this._size = this.size + 1;
inserted = this.root;
} else {
let cur = this.root;
@ -94,7 +93,7 @@ export class BST<V = any, N extends BSTNode<V, N> = BSTNode<V, BSTNodeNested<V>>
}
//Add to the left of the current node
cur.left = newNode;
this._setSize(this.size + 1);
this._size = this.size + 1;
traversing = false;
inserted = cur.left;
} else {
@ -109,7 +108,7 @@ export class BST<V = any, N extends BSTNode<V, N> = BSTNode<V, BSTNodeNested<V>>
}
//Add to the right of the current node
cur.right = newNode;
this._setSize(this.size + 1);
this._size = this.size + 1;
traversing = false;
inserted = cur.right;
} else {

View file

@ -5,24 +5,16 @@ import {BST, BSTNode} from './bst';
export class RBTreeNode<V = any, N extends RBTreeNode<V, N> = RBTreeNodeNested<V>> extends BSTNode<V, N> {
constructor(key: BTNKey, value?: V) {
super(key, value);
this._color = RBColor.RED;
this.color = RBColor.RED;
}
private _color: RBColor;
color: RBColor;
get color(): RBColor {
return this._color;
}
set color(value: RBColor) {
this._color = value;
}
}
export class RBTree<V, N extends RBTreeNode<V, N> = RBTreeNode<V, RBTreeNodeNested<V>>>
extends BST<V, N>
implements IBinaryTree<V, N>
{
implements IBinaryTree<V, N> {
constructor(options?: RBTreeOptions) {
super(options);
}
@ -38,7 +30,7 @@ export class RBTree<V, N extends RBTreeNode<V, N> = RBTreeNode<V, RBTreeNodeNest
// }
//
// // Method for fixing insert violations in a red-black tree
// private _fixInsertViolation(node: N) {
// protected _fixInsertViolation(node: N) {
// while (node !== this.root! && node.color === RBColor.RED && node.parent!.color === RBColor.RED) {
// const parent = node.parent!;
// const grandparent = parent.parent!;
@ -101,7 +93,7 @@ export class RBTree<V, N extends RBTreeNode<V, N> = RBTreeNode<V, RBTreeNodeNest
// }
//
// // Left rotation operation
// private _rotateLeft(node: N) {
// protected _rotateLeft(node: N) {
// const rightChild = node.right;
// node.right = rightChild!.left;
//
@ -125,7 +117,7 @@ export class RBTree<V, N extends RBTreeNode<V, N> = RBTreeNode<V, RBTreeNodeNest
// }
//
// // Right rotation operation
// private _rotateRight(node: N) {
// protected _rotateRight(node: N) {
// const leftChild = node.left;
// node.left = leftChild!.right;
//
@ -148,12 +140,12 @@ export class RBTree<V, N extends RBTreeNode<V, N> = RBTreeNode<V, RBTreeNodeNest
// node.parent = leftChild;
// }
//
// private _isNodeRed(node: N | null | undefined): boolean {
// protected _isNodeRed(node: N | null | undefined): boolean {
// return node ? node.color === RBColor.RED : false;
// }
//
// // Find the sibling node
// private _findSibling(node: N): N | null | undefined {
// protected _findSibling(node: N): N | null | undefined {
// if (!node.parent) {
// return undefined;
// }
@ -162,7 +154,7 @@ export class RBTree<V, N extends RBTreeNode<V, N> = RBTreeNode<V, RBTreeNodeNest
// }
//
// // Remove a node
// private _removeNode(node: N, replacement: N | null | undefined): void {
// protected _removeNode(node: N, replacement: N | null | undefined): void {
// if (node === this.root && !replacement) {
// // If there's only the root node and no replacement, simply delete the root node
// this._setRoot(null);
@ -230,7 +222,7 @@ export class RBTree<V, N extends RBTreeNode<V, N> = RBTreeNode<V, RBTreeNodeNest
// }
//
// // Repair operation after node deletion
// private _fixDeleteViolation(node: N | null | undefined) {
// protected _fixDeleteViolation(node: N | null | undefined) {
// let sibling;
//
// while (node && node !== this.root && !this._isNodeRed(node)) {
@ -327,7 +319,7 @@ export class RBTree<V, N extends RBTreeNode<V, N> = RBTreeNode<V, RBTreeNodeNest
// }
// }
//
// private _findMin(node: N): N {
// protected _findMin(node: N): N {
// while (node.left) {
// node = node.left;
// }
@ -335,7 +327,7 @@ export class RBTree<V, N extends RBTreeNode<V, N> = RBTreeNode<V, RBTreeNodeNest
// }
//
// // Get the replacement node
// private _getReplacementNode(node: N): N | null | undefined {
// protected _getReplacementNode(node: N): N | null | undefined {
// if (node.left && node.right) {
// return this._findSuccessor(node);
// }
@ -348,7 +340,7 @@ export class RBTree<V, N extends RBTreeNode<V, N> = RBTreeNode<V, RBTreeNodeNest
// }
//
// // Find the successor node
// private _findSuccessor(node: N): N | null | undefined {
// protected _findSuccessor(node: N): N | null | undefined {
// if (node.right) {
// // If the node has a right child, find the minimum node in the right subtree as the successor
// return this._findMin(node.right);

View file

@ -9,70 +9,18 @@
import type {SegmentTreeNodeVal} from '../../types';
export class SegmentTreeNode {
start = 0;
end = 0;
value: SegmentTreeNodeVal | null = null;
sum = 0;
left: SegmentTreeNode | null = null;
right: SegmentTreeNode | null = null;
constructor(start: number, end: number, sum: number, value?: SegmentTreeNodeVal | null) {
this._start = start;
this._end = end;
this._sum = sum;
this._value = value || null;
}
private _start = 0;
get start(): number {
return this._start;
}
set start(v: number) {
this._start = v;
}
private _end = 0;
get end(): number {
return this._end;
}
set end(v: number) {
this._end = v;
}
private _value: SegmentTreeNodeVal | null = null;
get value(): SegmentTreeNodeVal | null {
return this._value;
}
set value(v: SegmentTreeNodeVal | null) {
this._value = v;
}
private _sum = 0;
get sum(): number {
return this._sum;
}
set sum(v: number) {
this._sum = v;
}
private _left: SegmentTreeNode | null = null;
get left(): SegmentTreeNode | null {
return this._left;
}
set left(v: SegmentTreeNode | null) {
this._left = v;
}
private _right: SegmentTreeNode | null = null;
get right(): SegmentTreeNode | null {
return this._right;
}
set right(v: SegmentTreeNode | null) {
this._right = v;
this.start = start;
this.end = end;
this.sum = sum;
this.value = value || null;
}
}
@ -101,24 +49,25 @@ export class SegmentTree {
}
}
private _values: number[] = [];
protected _values: number[] = [];
get values(): number[] {
return this._values;
}
private _start = 0;
protected _start = 0;
get start(): number {
return this._start;
}
private _end: number;
protected _end: number;
get end(): number {
return this._end;
}
private _root: SegmentTreeNode | null;
protected _root: SegmentTreeNode | null;
get root(): SegmentTreeNode | null {
return this._root;
@ -238,20 +187,4 @@ export class SegmentTree {
};
return dfs(root, indexA, indexB);
}
protected _setValues(value: number[]) {
this._values = value;
}
protected _setStart(value: number) {
this._start = value;
}
protected _setEnd(value: number) {
this._end = value;
}
protected _setRoot(v: SegmentTreeNode | null) {
this._root = v;
}
}

View file

@ -6,7 +6,7 @@
* @license MIT License
*/
import type {BTNKey, TreeMultisetNodeNested, TreeMultisetOptions} from '../../types';
import {BinaryTreeDeletedResult, CP, FamilyPosition, IterationType, BTNCallback} from '../../types';
import {BinaryTreeDeletedResult, BTNCallback, CP, FamilyPosition, IterationType} from '../../types';
import {IBinaryTree} from '../../interfaces';
import {AVLTree, AVLTreeNode} from './avl-tree';
@ -37,8 +37,7 @@ export class TreeMultisetNode<
*/
export class TreeMultiset<V = any, N extends TreeMultisetNode<V, N> = TreeMultisetNode<V, TreeMultisetNodeNested<V>>>
extends AVLTree<V, N>
implements IBinaryTree<V, N>
{
implements IBinaryTree<V, N> {
/**
* The constructor function for a TreeMultiset class in TypeScript, which extends another class and sets an option to
* merge duplicated values.
@ -93,7 +92,7 @@ export class TreeMultiset<V = any, N extends TreeMultisetNode<V, N> = TreeMultis
}
if (!this.root) {
this._setRoot(newNode);
this._setSize(this.size + 1);
this._size = this.size + 1;
newNode && this._setCount(this.count + newNode.count);
inserted = this.root;
} else {
@ -113,7 +112,7 @@ export class TreeMultiset<V = any, N extends TreeMultisetNode<V, N> = TreeMultis
if (cur.left === undefined) {
//Add to the left of the current node
cur.left = newNode;
this._setSize(this.size + 1);
this._size = this.size + 1;
this._setCount(this.count + newNode.count);
traversing = false;
@ -127,7 +126,7 @@ export class TreeMultiset<V = any, N extends TreeMultisetNode<V, N> = TreeMultis
if (cur.right === undefined) {
//Add to the right of the current node
cur.right = newNode;
this._setSize(this.size + 1);
this._size = this.size + 1;
this._setCount(this.count + newNode.count);
traversing = false;
@ -162,7 +161,7 @@ export class TreeMultiset<V = any, N extends TreeMultisetNode<V, N> = TreeMultis
if (parent.left === undefined) {
parent.left = newNode;
if (newNode !== null) {
this._setSize(this.size + 1);
this._size = this.size + 1;
this._setCount(this.count + newNode.count);
}
@ -170,7 +169,7 @@ export class TreeMultiset<V = any, N extends TreeMultisetNode<V, N> = TreeMultis
} else if (parent.right === undefined) {
parent.right = newNode;
if (newNode !== null) {
this._setSize(this.size + 1);
this._size = (this.size + 1);
this._setCount(this.count + newNode.count);
}
return parent.right;
@ -321,7 +320,7 @@ export class TreeMultiset<V = any, N extends TreeMultisetNode<V, N> = TreeMultis
}
}
}
this._setSize(this.size - 1);
this._size = this.size - 1;
// TODO How to handle when the count of target node is lesser than current node's count
this._setCount(this.count - orgCurrent.count);
}

View file

@ -12,6 +12,9 @@ import {IGraph} from '../../interfaces';
import {Queue} from '../queue';
export abstract class AbstractVertex<V = any> {
key: VertexKey;
value: V | undefined;
/**
* The function is a protected constructor that takes an key and an optional value as parameters.
* @param {VertexKey} key - The `key` parameter is of type `VertexKey` and represents the identifier of the vertex. It is
@ -20,32 +23,16 @@ export abstract class AbstractVertex<V = any> {
* vertex. If no value is provided, it will be set to undefined.
*/
protected constructor(key: VertexKey, value?: V) {
this._key = key;
this._value = value;
this.key = key;
this.value = value;
}
private _key: VertexKey;
get key(): VertexKey {
return this._key;
}
set key(v: VertexKey) {
this._key = v;
}
private _value: V | undefined;
get value(): V | undefined {
return this._value;
}
set value(value: V | undefined) {
this._value = value;
}
}
export abstract class AbstractEdge<E = any> {
value: E | undefined;
weight: number;
/**
* The above function is a protected constructor that initializes the weight, value, and hash code properties of an
* object.
@ -56,31 +43,11 @@ export abstract class AbstractEdge<E = any> {
* meaning it can be omitted when creating an instance of the class.
*/
protected constructor(weight?: number, value?: E) {
this._weight = weight !== undefined ? weight : 1;
this._value = value;
this.weight = weight !== undefined ? weight : 1;
this.value = value;
this._hashCode = uuidV4();
}
private _value: E | undefined;
get value(): E | undefined {
return this._value;
}
set value(value: E | undefined) {
this._value = value;
}
private _weight: number;
get weight(): number {
return this._weight;
}
set weight(v: number) {
this._weight = v;
}
protected _hashCode: string;
get hashCode(): string {
@ -91,15 +58,6 @@ export abstract class AbstractEdge<E = any> {
* In TypeScript, a subclass inherits the interface implementation of its parent class, without needing to implement the same interface again in the subclass. This behavior differs from Java's approach. In Java, if a parent class implements an interface, the subclass needs to explicitly implement the same interface, even if the parent class has already implemented it.
* This means that using abstract methods in the parent class cannot constrain the grandchild classes. Defining methods within an interface also cannot constrain the descendant classes. When inheriting from this class, developers need to be aware that this method needs to be overridden.
*/
/**
* The function sets the value of the _hashCode property to the provided string.
* @param {string} v - The parameter "v" is of type string and represents the value that will be assigned to the
* "_hashCode" property.
*/
protected _setHashCode(v: string) {
this._hashCode = v;
}
}
export abstract class AbstractGraph<
@ -107,9 +65,8 @@ export abstract class AbstractGraph<
E = any,
VO extends AbstractVertex<V> = AbstractVertex<V>,
EO extends AbstractEdge<E> = AbstractEdge<E>
> implements IGraph<V, E, VO, EO>
{
private _vertices: Map<VertexKey, VO> = new Map<VertexKey, VO>();
> implements IGraph<V, E, VO, EO> {
protected _vertices: Map<VertexKey, VO> = new Map<VertexKey, VO>();
get vertices(): Map<VertexKey, VO> {
return this._vertices;
@ -556,14 +513,14 @@ export abstract class AbstractGraph<
}
getMinDist &&
distMap.forEach((d, v) => {
if (v !== srcVertex) {
if (d < minDist) {
minDist = d;
if (genPaths) minDest = v;
}
distMap.forEach((d, v) => {
if (v !== srcVertex) {
if (d < minDist) {
minDist = d;
if (genPaths) minDest = v;
}
});
}
});
genPaths && getPaths(minDest);
@ -625,7 +582,7 @@ 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});
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);
@ -854,7 +811,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
*/
floyd(): {costs: number[][]; predecessor: (VO | null)[][]} {
floyd(): { costs: number[][]; predecessor: (VO | null)[][] } {
const idAndVertices = [...this._vertices];
const n = idAndVertices.length;
@ -1040,7 +997,4 @@ export abstract class AbstractGraph<
return vertexOrKey instanceof AbstractVertex ? vertexOrKey.key : vertexOrKey;
}
protected _setVertices(value: Map<VertexKey, VO>) {
this._vertices = value;
}
}

View file

@ -24,6 +24,9 @@ export class DirectedVertex<V = any> extends AbstractVertex<V> {
}
export class DirectedEdge<E = any> extends AbstractEdge<E> {
src: VertexKey;
dest: VertexKey;
/**
* The constructor function initializes the source and destination vertices of an edge, along with an optional weight
* and value.
@ -37,40 +40,19 @@ export class DirectedEdge<E = any> extends AbstractEdge<E> {
*/
constructor(src: VertexKey, dest: VertexKey, weight?: number, value?: E) {
super(weight, value);
this._src = src;
this._dest = dest;
}
private _src: VertexKey;
get src(): VertexKey {
return this._src;
}
set src(v: VertexKey) {
this._src = v;
}
private _dest: VertexKey;
get dest(): VertexKey {
return this._dest;
}
set dest(v: VertexKey) {
this._dest = v;
this.src = src;
this.dest = dest;
}
}
export class DirectedGraph<
V = any,
E = any,
VO extends DirectedVertex<V> = DirectedVertex<V>,
EO extends DirectedEdge<E> = DirectedEdge<E>
>
V = any,
E = any,
VO extends DirectedVertex<V> = DirectedVertex<V>,
EO extends DirectedEdge<E> = DirectedEdge<E>
>
extends AbstractGraph<V, E, VO, EO>
implements IGraph<V, E, VO, EO>
{
implements IGraph<V, E, VO, EO> {
/**
* The constructor function initializes an instance of a class.
*/
@ -78,13 +60,13 @@ export class DirectedGraph<
super();
}
private _outEdgeMap: Map<VO, EO[]> = new Map<VO, EO[]>();
protected _outEdgeMap: Map<VO, EO[]> = new Map<VO, EO[]>();
get outEdgeMap(): Map<VO, EO[]> {
return this._outEdgeMap;
}
private _inEdgeMap: Map<VO, EO[]> = new Map<VO, EO[]>();
protected _inEdgeMap: Map<VO, EO[]> = new Map<VO, EO[]>();
get inEdgeMap(): Map<VO, EO[]> {
return this._inEdgeMap;
@ -464,12 +446,4 @@ export class DirectedGraph<
return false;
}
}
protected _setOutEdgeMap(value: Map<VO, EO[]>) {
this._outEdgeMap = value;
}
protected _setInEdgeMap(value: Map<VO, EO[]>) {
this._inEdgeMap = value;
}
}

View file

@ -2,6 +2,9 @@ import {MapGraphCoordinate, VertexKey} from '../../types';
import {DirectedEdge, DirectedGraph, DirectedVertex} from './directed-graph';
export class MapVertex<V = any> extends DirectedVertex<V> {
lat: number;
long: number;
/**
* The constructor function initializes an object with an key, latitude, longitude, and an optional value.
* @param {VertexKey} key - The `key` parameter is of type `VertexKey` and represents the identifier of the vertex.
@ -16,28 +19,8 @@ export class MapVertex<V = any> extends DirectedVertex<V> {
*/
constructor(key: VertexKey, value: V, lat: number, long: number) {
super(key, value);
this._lat = lat;
this._long = long;
}
private _lat: number;
get lat(): number {
return this._lat;
}
set lat(value: number) {
this._lat = value;
}
private _long: number;
get long(): number {
return this._long;
}
set long(value: number) {
this._long = value;
this.lat = lat;
this.long = long;
}
}
@ -78,26 +61,18 @@ export class MapGraph<
this._bottomRight = bottomRight;
}
private _origin: MapGraphCoordinate = [0, 0];
protected _origin: MapGraphCoordinate = [0, 0];
get origin(): MapGraphCoordinate {
return this._origin;
}
set origin(value: MapGraphCoordinate) {
this._origin = value;
}
private _bottomRight: MapGraphCoordinate | undefined;
protected _bottomRight: MapGraphCoordinate | undefined;
get bottomRight(): MapGraphCoordinate | undefined {
return this._bottomRight;
}
set bottomRight(value: MapGraphCoordinate | undefined) {
this._bottomRight = value;
}
/**
* The function creates a new vertex with the given key, value, latitude, and longitude.
* @param {VertexKey} key - The key parameter is the unique identifier for the vertex. It is of type VertexKey, which could

View file

@ -24,6 +24,8 @@ export class UndirectedVertex<V = any> extends AbstractVertex<V> {
}
export class UndirectedEdge<E = number> extends AbstractEdge<E> {
vertices: [VertexKey, VertexKey];
/**
* The constructor function creates an instance of a class with two vertex IDs, an optional weight, and an optional
* value.
@ -36,29 +38,18 @@ export class UndirectedEdge<E = number> extends AbstractEdge<E> {
*/
constructor(v1: VertexKey, v2: VertexKey, weight?: number, value?: E) {
super(weight, value);
this._vertices = [v1, v2];
}
private _vertices: [VertexKey, VertexKey];
get vertices() {
return this._vertices;
}
set vertices(v: [VertexKey, VertexKey]) {
this._vertices = v;
this.vertices = [v1, v2];
}
}
export class UndirectedGraph<
V = any,
E = any,
VO extends UndirectedVertex<V> = UndirectedVertex<V>,
EO extends UndirectedEdge<E> = UndirectedEdge<E>
>
V = any,
E = any,
VO extends UndirectedVertex<V> = UndirectedVertex<V>,
EO extends UndirectedEdge<E> = UndirectedEdge<E>
>
extends AbstractGraph<V, E, VO, EO>
implements IGraph<V, E, VO, EO>
{
implements IGraph<V, E, VO, EO> {
/**
* The constructor initializes a new Map object to store edges.
*/
@ -265,12 +256,4 @@ export class UndirectedGraph<
}
return true;
}
/**
* The function sets the edges of a graph.
* @param v - A map where the keys are of type VO and the values are arrays of type EO.
*/
protected _setEdges(v: Map<VO, EO[]>) {
this._edges = v;
}
}

View file

@ -133,7 +133,7 @@ export class HashMap<K, V> {
}
}
*entries(): IterableIterator<[K, V]> {
* entries(): IterableIterator<[K, V]> {
for (const bucket of this.table) {
if (bucket) {
for (const [key, value] of bucket) {

View file

@ -1 +1,2 @@
export class TreeMap {}
export class TreeMap {
}

View file

@ -1 +1,2 @@
export class TreeSet {}
export class TreeSet {
}

View file

@ -8,7 +8,7 @@
import type {Comparator, DFSOrderPattern} from '../../types';
export class Heap<E = any> {
constructor(options: {comparator: Comparator<E>; nodes?: E[]}) {
constructor(options: { comparator: Comparator<E>; nodes?: E[] }) {
this._comparator = options.comparator;
if (options.nodes && options.nodes.length > 0) {
this._nodes = options.nodes;
@ -48,7 +48,7 @@ export class Heap<E = any> {
* @returns A new Heap instance.
* @param options
*/
static heapify<E>(options: {nodes: E[]; comparator: Comparator<E>}): Heap<E> {
static heapify<E>(options: { nodes: E[]; comparator: Comparator<E> }): Heap<E> {
return new Heap<E>(options);
}

View file

@ -11,7 +11,7 @@ import type {Comparator} from '../../types';
export class MaxHeap<E = any> extends Heap<E> {
constructor(
options: {comparator: Comparator<E>; nodes?: E[]} = {
options: { comparator: Comparator<E>; 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');

View file

@ -11,7 +11,7 @@ import type {Comparator} from '../../types';
export class MinHeap<E = any> extends Heap<E> {
constructor(
options: {comparator: Comparator<E>; nodes?: E[]} = {
options: { comparator: Comparator<E>; 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');

View file

@ -594,7 +594,7 @@ export class DoublyLinkedList<E = any> {
/**
* The function returns an iterator that iterates over the values of a linked list.
*/
*[Symbol.iterator]() {
* [Symbol.iterator]() {
let current = this.head;
while (current) {

View file

@ -565,7 +565,7 @@ export class SinglyLinkedList<E = any> {
/**
* The function returns an iterator that iterates over the values of a linked list.
*/
*[Symbol.iterator]() {
* [Symbol.iterator]() {
let current = this.head;
while (current) {

View file

@ -7,14 +7,14 @@
*/
// todo need to be improved
export class MatrixNTI2D<V = any> {
private readonly _matrix: Array<Array<V>>;
protected readonly _matrix: Array<Array<V>>;
/**
* The constructor creates a matrix with the specified number of rows and columns, and initializes all elements to a
* given initial value or 0 if not provided.
* @param options - An object containing the following properties:
*/
constructor(options: {row: number; col: number; initialVal?: V}) {
constructor(options: { row: number; col: number; initialVal?: V }) {
const {row, col, initialVal} = options;
this._matrix = new Array(row).fill(undefined).map(() => new Array(col).fill(initialVal || 0));
}

View file

@ -8,7 +8,7 @@
import {Vector2D} from './vector2d';
export class Matrix2D {
private readonly _matrix: number[][];
protected readonly _matrix: number[][];
/**
* The constructor function initializes a Matrix2D object with either a default identity matrix, or a provided matrix

View file

@ -27,10 +27,10 @@ export class Character {
export class Navigator<T = number> {
onMove: (cur: [number, number]) => void;
private readonly _matrix: T[][];
private readonly _cur: [number, number];
private _character: Character;
private readonly _VISITED: T;
protected readonly _matrix: T[][];
protected readonly _cur: [number, number];
protected _character: Character;
protected readonly _VISITED: T;
/**
* The constructor initializes the Navigator object with the given parameters and sets the current position as visited

View file

@ -10,7 +10,8 @@ export class Vector2D {
public x: number = 0,
public y: number = 0,
public w: number = 1 // needed for matrix multiplication
) {}
) {
}
/**
* The function checks if the x and y values of a point are both zero.

View file

@ -10,7 +10,7 @@ import type {Comparator} from '../../types';
export class MaxPriorityQueue<E = any> extends PriorityQueue<E> {
constructor(
options: {comparator: Comparator<E>; nodes?: E[]} = {
options: { comparator: Comparator<E>; 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');

View file

@ -10,7 +10,7 @@ import type {Comparator} from '../../types';
export class MinPriorityQueue<E = any> extends PriorityQueue<E> {
constructor(
options: {comparator: Comparator<E>; nodes?: E[]} = {
options: { comparator: Comparator<E>; 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');

View file

@ -10,7 +10,7 @@ import {Heap} from '../heap';
import {Comparator} from '../../types';
export class PriorityQueue<E = any> extends Heap<E> {
constructor(options: {comparator: Comparator<E>; nodes?: E[]}) {
constructor(options: { comparator: Comparator<E>; nodes?: E[] }) {
super(options);
}
}

View file

@ -9,7 +9,8 @@ import {DoublyLinkedList} from '../linked-list';
// O(n) time complexity of obtaining the value
// O(1) time complexity of adding at the beginning and the end
export class Deque<E = any> extends DoublyLinkedList<E> {}
export class Deque<E = any> extends DoublyLinkedList<E> {
}
// O(1) time complexity of obtaining the value
// O(n) time complexity of adding at the beginning and the end
@ -19,9 +20,9 @@ export class ObjectDeque<E = number> {
if (capacity !== undefined) this._capacity = capacity;
}
protected _nodes: {[key: number]: E} = {};
protected _nodes: { [key: number]: E } = {};
get nodes(): {[p: number]: E} {
get nodes(): { [p: number]: E } {
return this._nodes;
}
@ -148,10 +149,11 @@ export class ObjectDeque<E = number> {
// O(1) time complexity of obtaining the value
// O(n) time complexity of adding at the beginning and the end
export class ArrayDeque<E> {
protected _nodes: E[] = [];
get nodes(): E[] {
return this._nodes;
}
protected _nodes: E[] = [];
get size() {
return this.nodes.length;

View file

@ -201,7 +201,7 @@ export class Queue<E = any> {
return new Queue(this.nodes.slice(this.offset));
}
*[Symbol.iterator]() {
* [Symbol.iterator]() {
for (const item of this.nodes) {
yield item;
}

View file

@ -4,11 +4,6 @@
* @class
*/
export class Stack<E = any> {
get elements(): E[] {
return this._elements;
}
protected _elements: E[];
/**
* The constructor initializes an array of elements, which can be provided as an optional parameter.
* @param {E[]} [elements] - The `elements` parameter is an optional parameter of type `E[]`, which represents an array
@ -19,6 +14,12 @@ export class Stack<E = any> {
this._elements = Array.isArray(elements) ? elements : [];
}
protected _elements: E[];
get elements(): E[] {
return this._elements;
}
/**
* The function "fromArray" creates a new Stack object from an array of elements.
* @param {E[]} elements - The `elements` parameter is an array of elements of type `E`.

View file

@ -1,16 +1,14 @@
export class TreeNode<V = any> {
key: string;
value?: V | undefined;
children?: TreeNode<V>[] | undefined;
constructor(key: string, value?: V, children?: TreeNode<V>[]) {
this.key = key;
this.value = value || undefined;
this.children = children || [];
}
key: string;
value?: V | undefined;
children?: TreeNode<V>[] | undefined;
addChildren(children: TreeNode<V> | TreeNode<V>[]) {
if (!this.children) {
this.children = [];

View file

@ -11,28 +11,21 @@
* and a flag indicating whether it's the end of a word.
*/
export class TrieNode {
key: string;
children: Map<string, TrieNode>;
isEnd: boolean;
constructor(key: string) {
this.key = key;
this.isEnd = false;
this.children = new Map<string, TrieNode>();
}
key: string;
children: Map<string, TrieNode>;
isEnd: boolean;
}
/**
* Trie represents a Trie data structure. It provides basic Trie operations and additional methods.
*/
export class Trie {
get caseSensitive(): boolean {
return this._caseSensitive;
}
protected _caseSensitive: boolean;
constructor(words?: string[], caseSensitive = true) {
this._root = new TrieNode('');
this._caseSensitive = caseSensitive;
@ -43,6 +36,12 @@ export class Trie {
}
}
protected _caseSensitive: boolean;
get caseSensitive(): boolean {
return this._caseSensitive;
}
protected _root: TrieNode;
get root() {

View file

@ -1,5 +1,5 @@
import {BinaryTreeNode} from '../data-structures';
import {BinaryTreeDeletedResult, BTNKey, BinaryTreeNodeNested, BTNCallback} from '../types';
import {BinaryTreeDeletedResult, BinaryTreeNodeNested, BTNCallback, BTNKey} from '../types';
export interface IBinaryTree<V = any, N extends BinaryTreeNode<V, N> = BinaryTreeNodeNested<V>> {
createNode(key: BTNKey, value?: N['value']): N;

View file

@ -1,5 +1,5 @@
import {BSTNode} from '../../../data-structures';
import type {BTNKey, BinaryTreeOptions} from './binary-tree';
import type {BinaryTreeOptions, BTNKey} from './binary-tree';
export type BSTComparator = (a: BTNKey, b: BTNKey) => number;

View file

@ -1,6 +1,6 @@
export type Direction = 'up' | 'right' | 'down' | 'left';
export type Turning = {[key in Direction]: Direction};
export type Turning = { [key in Direction]: Direction };
export type NavigatorParams<T = any> = {
matrix: T[][];

View file

@ -1,5 +1,5 @@
export type ToThunkFn = () => ReturnType<TrlFn>;
export type Thunk = () => ReturnType<ToThunkFn> & {__THUNK__: symbol};
export type Thunk = () => ReturnType<ToThunkFn> & { __THUNK__: symbol };
export type TrlFn = (...args: any[]) => any;
export type TrlAsyncFn = (...args: any[]) => any;

View file

@ -1,6 +1,6 @@
export type KeyValueObject = {[key: string]: any};
export type KeyValueObject = { [key: string]: any };
export type KeyValueObjectWithKey = {[key: string]: any; key: string | number | symbol};
export type KeyValueObjectWithKey = { [key: string]: any; key: string | number | symbol };
export type NonNumberNonObjectButDefined = string | boolean | symbol | null;

View file

@ -286,8 +286,8 @@ function loopLowerBoundTests(bit: BinaryIndexedTree, values: number[]) {
describe('', () => {
class NumArrayDC {
private _tree: BinaryIndexedTree;
private readonly _nums: number[];
protected _tree: BinaryIndexedTree;
protected readonly _nums: number[];
constructor(nums: number[]) {
this._nums = nums;

View file

@ -19,7 +19,6 @@ class MyEdge<E = any> extends AbstractEdge<E> {
this.src = srcOrV1;
this.dest = destOrV2;
this.data = value;
this._setHashCode('');
}
}
@ -96,6 +95,6 @@ describe('AbstractGraph Operation Test', () => {
eAB!.value = eAB.value;
const hs = eAB.hashCode;
expect(hs).toBe('');
expect(hs.length).toBe(36);
});
});

View file

@ -98,7 +98,7 @@ class MyVertex<V = any> extends DirectedVertex<V> {
this._data = value;
}
private _data: V | undefined;
protected _data: V | undefined;
get data(): V | undefined {
return this._data;
@ -115,7 +115,7 @@ class MyEdge<E = any> extends DirectedEdge<E> {
this._data = value;
}
private _data: E | undefined;
protected _data: E | undefined;
get data(): E | undefined {
return this._data;
@ -141,11 +141,11 @@ class MyDirectedGraph<
}
setInEdgeMap(value: Map<VO, EO[]>) {
super._setInEdgeMap(value);
this._inEdgeMap = value;
}
setOutEdgeMap(value: Map<VO, EO[]>) {
super._setOutEdgeMap(value);
this._outEdgeMap = value;
}
}

View file

@ -88,8 +88,8 @@ describe('MapGraph', () => {
const edgeAB = new MapEdge('A', 'B', 50, 'Edge from A to B');
const edgeBC = new MapEdge('B', 'C', 60, 'Edge from B to C');
mapGraph.origin = mapGraph.origin;
mapGraph.bottomRight = mapGraph.bottomRight;
expect(mapGraph.origin).toEqual([0, 0]);
expect(mapGraph.bottomRight).toEqual([100, 100]);
mapGraph.addVertex(locationA);
mapGraph.addVertex(locationB);