Socket
Socket
Sign inDemoInstall

heap-typed

Package Overview
Dependencies
Maintainers
1
Versions
153
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

heap-typed - npm Package Compare versions

Comparing version 1.49.4 to 1.49.5

2

dist/data-structures/base/iterable-base.d.ts

@@ -1,2 +0,2 @@

import { ElementCallback, EntryCallback, ReduceElementCallback, ReduceEntryCallback } from "../../types";
import { ElementCallback, EntryCallback, ReduceElementCallback, ReduceEntryCallback } from '../../types';
export declare abstract class IterableEntryBase<K = any, V = any> {

@@ -3,0 +3,0 @@ /**

@@ -11,3 +11,3 @@ /**

import { IBinaryTree } from '../../interfaces';
import { IterableEntryBase } from "../base";
import { IterableEntryBase } from '../base';
/**

@@ -547,14 +547,2 @@ * Represents a node in a binary tree.

/**
* The function `_addTo` adds a new node to a binary tree if there is an available position.
* @param {N | null | undefined} newNode - The `newNode` parameter represents the node that you want to add to
* the binary tree. It can be either a node object or `null`.
* @param {N} parent - The `parent` parameter represents the parent node to which the new node will
* be added as a child.
* @returns either the left or right child node of the parent node, depending on which child is
* available for adding the new node. If a new node is added, the function also updates the size of
* the binary tree. If neither the left nor right child is available, the function returns undefined.
* If the parent node is null, the function also returns undefined.
*/
protected _addTo(newNode: N | null | undefined, parent: BTNKeyOrNode<K, N>): N | null | undefined;
/**
* The function sets the root property of an object to a given value, and if the value is not null,

@@ -561,0 +549,0 @@ * it also sets the parent property of the value to undefined.

@@ -167,18 +167,2 @@ /**

/**
* Time Complexity: O(1) - constant time, as it performs basic pointer assignments.
* Space Complexity: O(1) - constant space, as it only uses a constant amount of memory.
*
* The function adds a new node to a binary tree, either as the left child or the right child of a
* given parent node.
* @param {N | undefined} newNode - The `newNode` parameter represents the node that needs to be
* added to the binary tree. It can be of type `N` (which represents a node in the binary tree) or
* `undefined` if there is no node to add.
* @param {K | N | undefined} parent - The `parent` parameter represents the parent node to
* which the new node will be added as a child. It can be either a node object (`N`) or a key value
* (`K`).
* @returns The method `_addTo` returns either the `parent.left` or `parent.right` node that was
* added, or `undefined` if no node was added.
*/
protected _addTo(newNode: N | undefined, parent: BSTNKeyOrNode<K, N>): N | undefined;
/**
* The `_swapProperties` function swaps the key, value, count, and height properties between two nodes.

@@ -185,0 +169,0 @@ * @param {K | N | undefined} srcNode - The `srcNode` parameter represents the source node from

@@ -36,3 +36,3 @@ "use strict";

let sum = 0;
this.subTreeTraverse(node => sum += node.count);
this.subTreeTraverse(node => (sum += node.count));
return sum;

@@ -317,44 +317,2 @@ }

/**
* Time Complexity: O(1) - constant time, as it performs basic pointer assignments.
* Space Complexity: O(1) - constant space, as it only uses a constant amount of memory.
*
* The function adds a new node to a binary tree, either as the left child or the right child of a
* given parent node.
* @param {N | undefined} newNode - The `newNode` parameter represents the node that needs to be
* added to the binary tree. It can be of type `N` (which represents a node in the binary tree) or
* `undefined` if there is no node to add.
* @param {K | N | undefined} parent - The `parent` parameter represents the parent node to
* which the new node will be added as a child. It can be either a node object (`N`) or a key value
* (`K`).
* @returns The method `_addTo` returns either the `parent.left` or `parent.right` node that was
* added, or `undefined` if no node was added.
*/
_addTo(newNode, parent) {
parent = this.ensureNode(parent);
if (parent) {
if (parent.left === undefined) {
parent.left = newNode;
if (newNode !== undefined) {
this._size = this.size + 1;
this._count += newNode.count;
}
return parent.left;
}
else if (parent.right === undefined) {
parent.right = newNode;
if (newNode !== undefined) {
this._size = this.size + 1;
this._count += newNode.count;
}
return parent.right;
}
else {
return;
}
}
else {
return;
}
}
/**
* The `_swapProperties` function swaps the key, value, count, and height properties between two nodes.

@@ -361,0 +319,0 @@ * @param {K | N | undefined} srcNode - The `srcNode` parameter represents the source node from

@@ -9,3 +9,3 @@ /**

import type { DijkstraResult, EntryCallback, VertexKey } from '../../types';
import { IterableEntryBase } from "../base";
import { IterableEntryBase } from '../base';
import { IGraph } from '../../interfaces';

@@ -12,0 +12,0 @@ export declare abstract class AbstractVertex<V = any> {

@@ -98,3 +98,3 @@ "use strict";

const potentialKeyType = typeof potentialKey;
return potentialKeyType === "string" || potentialKeyType === "number";
return potentialKeyType === 'string' || potentialKeyType === 'number';
}

@@ -1019,3 +1019,4 @@ /**

if (visited.has(vertex)) {
if ((!isInclude2Cycle && currentPath.length > 2 || isInclude2Cycle && currentPath.length >= 2) && currentPath[0] === vertex.key) {
if (((!isInclude2Cycle && currentPath.length > 2) || (isInclude2Cycle && currentPath.length >= 2)) &&
currentPath[0] === vertex.key) {
cycles.push([...currentPath]);

@@ -1022,0 +1023,0 @@ }

@@ -124,3 +124,3 @@ /**

protected _hashFn: (key: K) => string;
protected _isObjKey(key: any): key is (object | ((...args: any[]) => any));
protected _isObjKey(key: any): key is object | ((...args: any[]) => any);
protected _getNoObjKey(key: K): string;

@@ -127,0 +127,0 @@ }

@@ -222,7 +222,7 @@ "use strict";

let strKey;
if (keyType !== "string" && keyType !== "number" && keyType !== "symbol") {
if (keyType !== 'string' && keyType !== 'number' && keyType !== 'symbol') {
strKey = this._hashFn(key);
}
else {
if (keyType === "number") {
if (keyType === 'number') {
// TODO numeric key should has its own hash

@@ -229,0 +229,0 @@ strKey = key;

@@ -404,7 +404,6 @@ "use strict";

while (index < halfLength) {
let left = index << 1 | 1;
let left = (index << 1) | 1;
const right = left + 1;
let minItem = this.elements[left];
if (right < this.elements.length &&
this.options.comparator(minItem, this.elements[right]) > 0) {
if (right < this.elements.length && this.options.comparator(minItem, this.elements[right]) > 0) {
left = right;

@@ -411,0 +410,0 @@ minItem = this.elements[right];

@@ -8,4 +8,4 @@ /**

*/
import type { ElementCallback } from "../../types";
import { IterableElementBase } from "../base";
import type { ElementCallback } from '../../types';
import { IterableElementBase } from '../base';
export declare class SinglyLinkedListNode<E = any> {

@@ -12,0 +12,0 @@ value: E;

export * from './matrix';
export * from './vector2d';
export * from './matrix2d';
export * from './navigator';

@@ -18,4 +18,2 @@ "use strict";

__exportStar(require("./matrix"), exports);
__exportStar(require("./vector2d"), exports);
__exportStar(require("./matrix2d"), exports);
__exportStar(require("./navigator"), exports);

@@ -8,15 +8,133 @@ /**

*/
export declare class MatrixNTI2D<V = any> {
protected readonly _matrix: Array<Array<V>>;
export declare class Matrix {
/**
* 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:
* The constructor function initializes a matrix object with the provided data and options, or with
* default values if no options are provided.
* @param {number[][]} data - A 2D array of numbers representing the data for the matrix.
* @param [options] - The `options` parameter is an optional object that can contain the following
* properties:
*/
constructor(options: {
row: number;
col: number;
initialVal?: V;
constructor(data: number[][], options?: {
rows?: number;
cols?: number;
addFn?: (a: number, b: number) => any;
subtractFn?: (a: number, b: number) => any;
multiplyFn?: (a: number, b: number) => any;
});
toArray(): Array<Array<V>>;
protected _rows: number;
get rows(): number;
protected _cols: number;
get cols(): number;
protected _data: number[][];
get data(): number[][];
get addFn(): (a: number | undefined, b: number) => number | undefined;
get subtractFn(): (a: number, b: number) => number;
get multiplyFn(): (a: number, b: number) => number;
/**
* The `get` function returns the value at the specified row and column index if it is a valid index.
* @param {number} row - The `row` parameter represents the row index of the element you want to
* retrieve from the data array.
* @param {number} col - The parameter "col" represents the column number of the element you want to
* retrieve from the data array.
* @returns The `get` function returns a number if the provided row and column indices are valid.
* Otherwise, it returns `undefined`.
*/
get(row: number, col: number): number | undefined;
/**
* The set function updates the value at a specified row and column in a two-dimensional array.
* @param {number} row - The "row" parameter represents the row index of the element in a
* two-dimensional array or matrix. It specifies the row where the value will be set.
* @param {number} col - The "col" parameter represents the column index of the element in a
* two-dimensional array.
* @param {number} value - The value parameter represents the number that you want to set at the
* specified row and column in the data array.
* @returns a boolean value. It returns true if the index (row, col) is valid and the value is
* successfully set in the data array. It returns false if the index is invalid and the value is not
* set.
*/
set(row: number, col: number, value: number): boolean;
/**
* The function checks if the dimensions of the given matrix match the dimensions of the current
* matrix.
* @param {Matrix} matrix - The parameter `matrix` is of type `Matrix`.
* @returns a boolean value.
*/
isMatchForCalculate(matrix: Matrix): boolean;
/**
* The `add` function adds two matrices together, returning a new matrix with the result.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
* @returns The `add` method returns a new `Matrix` object that represents the result of adding the
* current matrix with the provided `matrix` parameter.
*/
add(matrix: Matrix): Matrix | undefined;
/**
* The `subtract` function performs element-wise subtraction between two matrices and returns a new
* matrix with the result.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class. It
* represents the matrix that you want to subtract from the current matrix.
* @returns a new Matrix object with the result of the subtraction operation.
*/
subtract(matrix: Matrix): Matrix | undefined;
/**
* The `multiply` function performs matrix multiplication between two matrices and returns the result
* as a new matrix.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
* @returns a new Matrix object.
*/
multiply(matrix: Matrix): Matrix | undefined;
/**
* The transpose function takes a matrix and returns a new matrix that is the transpose of the
* original matrix.
* @returns The transpose() function returns a new Matrix object with the transposed data.
*/
transpose(): Matrix;
/**
* The `inverse` function calculates the inverse of a square matrix using Gaussian elimination.
* @returns a Matrix object, which represents the inverse of the original matrix.
*/
inverse(): Matrix | undefined;
/**
* The dot function calculates the dot product of two matrices and returns a new matrix.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
* @returns a new Matrix object.
*/
dot(matrix: Matrix): Matrix | undefined;
protected _addFn(a: number | undefined, b: number): number | undefined;
protected _subtractFn(a: number, b: number): number;
protected _multiplyFn(a: number, b: number): number;
/**
* The function checks if a given row and column index is valid within a specified range.
* @param {number} row - The `row` parameter represents the row index of a two-dimensional array or
* matrix. It is a number that indicates the specific row in the matrix.
* @param {number} col - The "col" parameter represents the column index in a two-dimensional array
* or grid. It is used to check if the given column index is valid within the bounds of the grid.
* @returns A boolean value is being returned.
*/
protected isValidIndex(row: number, col: number): boolean;
/**
* The function `_swapRows` swaps the positions of two rows in an array.
* @param {number} row1 - The `row1` parameter is the index of the first row that you want to swap.
* @param {number} row2 - The `row2` parameter is the index of the second row that you want to swap
* with the first row.
*/
protected _swapRows(row1: number, row2: number): void;
/**
* The function scales a specific row in a matrix by a given scalar value.
* @param {number} row - The `row` parameter represents the index of the row in the matrix that you
* want to scale. It is a number that indicates the position of the row within the matrix.
* @param {number} scalar - The scalar parameter is a number that is used to multiply each element in
* a specific row of a matrix.
*/
protected _scaleRow(row: number, scalar: number): void;
/**
* The function `_addScaledRow` multiplies a row in a matrix by a scalar value and adds it to another
* row.
* @param {number} targetRow - The targetRow parameter represents the index of the row in which the
* scaled values will be added.
* @param {number} sourceRow - The sourceRow parameter represents the index of the row from which the
* values will be scaled and added to the targetRow.
* @param {number} scalar - The scalar parameter is a number that is used to scale the values in the
* source row before adding them to the target row.
*/
protected _addScaledRow(targetRow: number, sourceRow: number, scalar: number): void;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MatrixNTI2D = void 0;
/**

@@ -11,19 +9,406 @@ * data-structure-typed

*/
// todo need to be improved
class MatrixNTI2D {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Matrix = void 0;
class Matrix {
/**
* 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:
* The constructor function initializes a matrix object with the provided data and options, or with
* default values if no options are provided.
* @param {number[][]} data - A 2D array of numbers representing the data for the matrix.
* @param [options] - The `options` parameter is an optional object that can contain the following
* properties:
*/
constructor(options) {
const { row, col, initialVal } = options;
this._matrix = new Array(row).fill(undefined).map(() => new Array(col).fill(initialVal || 0));
constructor(data, options) {
var _a, _b, _c;
this._rows = 0;
this._cols = 0;
if (options) {
const { rows, cols, addFn, subtractFn, multiplyFn } = options;
if (typeof rows === 'number' && rows > 0)
this._rows = rows;
else
this._rows = data.length;
if (typeof cols === 'number' && cols > 0)
this._cols = cols;
else
this._cols = ((_a = data[0]) === null || _a === void 0 ? void 0 : _a.length) || 0;
if (addFn)
this._addFn = addFn;
if (subtractFn)
this._subtractFn = subtractFn;
if (multiplyFn)
this._multiplyFn = multiplyFn;
}
else {
this._rows = data.length;
this._cols = (_c = (_b = data[0]) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0;
}
if (data.length > 0) {
this._data = data;
}
else {
this._data = [];
for (let i = 0; i < this.rows; i++) {
this._data[i] = new Array(this.cols).fill(0);
}
}
}
/* The `toArray` method returns the matrix as a two-dimensional array. It converts the internal representation of the
matrix, which is an array of arrays, into a format that is more commonly used in JavaScript. */
toArray() {
return this._matrix;
get rows() {
return this._rows;
}
get cols() {
return this._cols;
}
get data() {
return this._data;
}
get addFn() {
return this._addFn;
}
get subtractFn() {
return this._subtractFn;
}
get multiplyFn() {
return this._multiplyFn;
}
/**
* The `get` function returns the value at the specified row and column index if it is a valid index.
* @param {number} row - The `row` parameter represents the row index of the element you want to
* retrieve from the data array.
* @param {number} col - The parameter "col" represents the column number of the element you want to
* retrieve from the data array.
* @returns The `get` function returns a number if the provided row and column indices are valid.
* Otherwise, it returns `undefined`.
*/
get(row, col) {
if (this.isValidIndex(row, col)) {
return this.data[row][col];
}
}
/**
* The set function updates the value at a specified row and column in a two-dimensional array.
* @param {number} row - The "row" parameter represents the row index of the element in a
* two-dimensional array or matrix. It specifies the row where the value will be set.
* @param {number} col - The "col" parameter represents the column index of the element in a
* two-dimensional array.
* @param {number} value - The value parameter represents the number that you want to set at the
* specified row and column in the data array.
* @returns a boolean value. It returns true if the index (row, col) is valid and the value is
* successfully set in the data array. It returns false if the index is invalid and the value is not
* set.
*/
set(row, col, value) {
if (this.isValidIndex(row, col)) {
this.data[row][col] = value;
return true;
}
return false;
}
/**
* The function checks if the dimensions of the given matrix match the dimensions of the current
* matrix.
* @param {Matrix} matrix - The parameter `matrix` is of type `Matrix`.
* @returns a boolean value.
*/
isMatchForCalculate(matrix) {
return this.rows === matrix.rows && this.cols === matrix.cols;
}
/**
* The `add` function adds two matrices together, returning a new matrix with the result.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
* @returns The `add` method returns a new `Matrix` object that represents the result of adding the
* current matrix with the provided `matrix` parameter.
*/
add(matrix) {
if (!this.isMatchForCalculate(matrix)) {
throw new Error('Matrix dimensions must match for addition.');
}
const resultData = [];
for (let i = 0; i < this.rows; i++) {
resultData[i] = [];
for (let j = 0; j < this.cols; j++) {
const a = this.get(i, j), b = matrix.get(i, j);
if (a !== undefined && b !== undefined) {
const added = this._addFn(a, b);
if (added) {
resultData[i][j] = added;
}
}
}
}
return new Matrix(resultData, {
rows: this.rows,
cols: this.cols,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
/**
* The `subtract` function performs element-wise subtraction between two matrices and returns a new
* matrix with the result.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class. It
* represents the matrix that you want to subtract from the current matrix.
* @returns a new Matrix object with the result of the subtraction operation.
*/
subtract(matrix) {
if (!this.isMatchForCalculate(matrix)) {
throw new Error('Matrix dimensions must match for subtraction.');
}
const resultData = [];
for (let i = 0; i < this.rows; i++) {
resultData[i] = [];
for (let j = 0; j < this.cols; j++) {
const a = this.get(i, j), b = matrix.get(i, j);
if (a !== undefined && b !== undefined) {
const subtracted = this._subtractFn(a, b);
if (subtracted) {
resultData[i][j] = subtracted;
}
}
}
}
return new Matrix(resultData, {
rows: this.rows,
cols: this.cols,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
/**
* The `multiply` function performs matrix multiplication between two matrices and returns the result
* as a new matrix.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
* @returns a new Matrix object.
*/
multiply(matrix) {
if (this.cols !== matrix.rows) {
throw new Error('Matrix dimensions must be compatible for multiplication (A.cols = B.rows).');
}
const resultData = [];
for (let i = 0; i < this.rows; i++) {
resultData[i] = [];
for (let j = 0; j < matrix.cols; j++) {
let sum;
for (let k = 0; k < this.cols; k++) {
const a = this.get(i, k), b = matrix.get(k, j);
if (a !== undefined && b !== undefined) {
const multiplied = this.multiplyFn(a, b);
if (multiplied !== undefined) {
sum = this.addFn(sum, multiplied);
}
}
}
if (sum !== undefined)
resultData[i][j] = sum;
}
}
return new Matrix(resultData, {
rows: this.rows,
cols: matrix.cols,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
/**
* The transpose function takes a matrix and returns a new matrix that is the transpose of the
* original matrix.
* @returns The transpose() function returns a new Matrix object with the transposed data.
*/
transpose() {
if (this.data.some(row => row.length !== this.rows)) {
throw new Error('Matrix must be rectangular for transposition.');
}
const resultData = [];
for (let j = 0; j < this.cols; j++) {
resultData[j] = [];
for (let i = 0; i < this.rows; i++) {
const trans = this.get(i, j);
if (trans !== undefined)
resultData[j][i] = trans;
}
}
return new Matrix(resultData, {
rows: this.cols,
cols: this.rows,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
/**
* The `inverse` function calculates the inverse of a square matrix using Gaussian elimination.
* @returns a Matrix object, which represents the inverse of the original matrix.
*/
inverse() {
var _a;
// Check if the matrix is square
if (this.rows !== this.cols) {
throw new Error('Matrix must be square for inversion.');
}
// Create an augmented matrix [this | I]
const augmentedMatrixData = [];
for (let i = 0; i < this.rows; i++) {
augmentedMatrixData[i] = this.data[i].slice(); // Copy the original matrix
for (let j = 0; j < this.cols; j++) {
augmentedMatrixData[i][this.cols + j] = i === j ? 1 : 0; // Append the identity matrix
}
}
const augmentedMatrix = new Matrix(augmentedMatrixData, {
rows: this.rows,
cols: this.cols * 2,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
// Apply Gaussian elimination to transform the left half into the identity matrix
for (let i = 0; i < this.rows; i++) {
// Find pivot
let pivotRow = i;
while (pivotRow < this.rows && augmentedMatrix.get(pivotRow, i) === 0) {
pivotRow++;
}
if (pivotRow === this.rows) {
// Matrix is singular, and its inverse does not exist
throw new Error('Matrix is singular, and its inverse does not exist.');
}
// Swap rows to make the pivot the current row
augmentedMatrix._swapRows(i, pivotRow);
// Scale the pivot row to make the pivot element 1
const pivotElement = (_a = augmentedMatrix.get(i, i)) !== null && _a !== void 0 ? _a : 1;
if (pivotElement === 0) {
// Handle division by zero
throw new Error('Matrix is singular, and its inverse does not exist (division by zero).');
}
augmentedMatrix._scaleRow(i, 1 / pivotElement);
// Eliminate other rows to make elements in the current column zero
for (let j = 0; j < this.rows; j++) {
if (j !== i) {
let factor = augmentedMatrix.get(j, i);
if (factor === undefined)
factor = 0;
augmentedMatrix._addScaledRow(j, i, -factor);
}
}
}
// Extract the right half of the augmented matrix as the inverse
const inverseData = [];
for (let i = 0; i < this.rows; i++) {
inverseData[i] = augmentedMatrix.data[i].slice(this.cols);
}
return new Matrix(inverseData, {
rows: this.rows,
cols: this.cols,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
/**
* The dot function calculates the dot product of two matrices and returns a new matrix.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
* @returns a new Matrix object.
*/
dot(matrix) {
if (this.cols !== matrix.rows) {
throw new Error('Number of columns in the first matrix must be equal to the number of rows in the second matrix for dot product.');
}
const resultData = [];
for (let i = 0; i < this.rows; i++) {
resultData[i] = [];
for (let j = 0; j < matrix.cols; j++) {
let sum;
for (let k = 0; k < this.cols; k++) {
const a = this.get(i, k), b = matrix.get(k, j);
if (a !== undefined && b !== undefined) {
const multiplied = this.multiplyFn(a, b);
if (multiplied !== undefined) {
sum = this.addFn(sum, multiplied);
}
}
}
if (sum !== undefined)
resultData[i][j] = sum;
}
}
return new Matrix(resultData, {
rows: this.rows,
cols: matrix.cols,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
_addFn(a, b) {
if (a === undefined)
return b;
return a + b;
}
_subtractFn(a, b) {
return a - b;
}
_multiplyFn(a, b) {
return a * b;
}
/**
* The function checks if a given row and column index is valid within a specified range.
* @param {number} row - The `row` parameter represents the row index of a two-dimensional array or
* matrix. It is a number that indicates the specific row in the matrix.
* @param {number} col - The "col" parameter represents the column index in a two-dimensional array
* or grid. It is used to check if the given column index is valid within the bounds of the grid.
* @returns A boolean value is being returned.
*/
isValidIndex(row, col) {
return row >= 0 && row < this.rows && col >= 0 && col < this.cols;
}
/**
* The function `_swapRows` swaps the positions of two rows in an array.
* @param {number} row1 - The `row1` parameter is the index of the first row that you want to swap.
* @param {number} row2 - The `row2` parameter is the index of the second row that you want to swap
* with the first row.
*/
_swapRows(row1, row2) {
const temp = this.data[row1];
this.data[row1] = this.data[row2];
this.data[row2] = temp;
}
/**
* The function scales a specific row in a matrix by a given scalar value.
* @param {number} row - The `row` parameter represents the index of the row in the matrix that you
* want to scale. It is a number that indicates the position of the row within the matrix.
* @param {number} scalar - The scalar parameter is a number that is used to multiply each element in
* a specific row of a matrix.
*/
_scaleRow(row, scalar) {
for (let j = 0; j < this.cols; j++) {
let multiplied = this.multiplyFn(this.data[row][j], scalar);
if (multiplied === undefined)
multiplied = 0;
this.data[row][j] = multiplied;
}
}
/**
* The function `_addScaledRow` multiplies a row in a matrix by a scalar value and adds it to another
* row.
* @param {number} targetRow - The targetRow parameter represents the index of the row in which the
* scaled values will be added.
* @param {number} sourceRow - The sourceRow parameter represents the index of the row from which the
* values will be scaled and added to the targetRow.
* @param {number} scalar - The scalar parameter is a number that is used to scale the values in the
* source row before adding them to the target row.
*/
_addScaledRow(targetRow, sourceRow, scalar) {
for (let j = 0; j < this.cols; j++) {
let multiplied = this.multiplyFn(this.data[sourceRow][j], scalar);
if (multiplied === undefined)
multiplied = 0;
const scaledValue = multiplied;
let added = this.addFn(this.data[targetRow][j], scaledValue);
if (added === undefined)
added = 0;
this.data[targetRow][j] = added;
}
}
}
exports.MatrixNTI2D = MatrixNTI2D;
exports.Matrix = Matrix;

@@ -8,4 +8,4 @@ /**

*/
import type { ElementCallback, IterableWithSizeOrLength } from "../../types";
import { IterableElementBase } from "../base";
import type { ElementCallback, IterableWithSizeOrLength } from '../../types';
import { IterableElementBase } from '../base';
/**

@@ -12,0 +12,0 @@ * 1. Operations at Both Ends: Supports adding and removing elements at both the front and back of the queue. This allows it to be used as a stack (last in, first out) and a queue (first in, first out).

@@ -23,3 +23,3 @@ "use strict";

*/
constructor(elements = [], bucketSize = (1 << 12)) {
constructor(elements = [], bucketSize = 1 << 12) {
super();

@@ -53,3 +53,3 @@ this._bucketFirst = 0;

this._bucketFirst = this._bucketLast = (this._bucketCount >> 1) - (needBucketNum >> 1);
this._firstInBucket = this._lastInBucket = (this._bucketSize - _size % this._bucketSize) >> 1;
this._firstInBucket = this._lastInBucket = (this._bucketSize - (_size % this._bucketSize)) >> 1;
for (const element of elements) {

@@ -106,4 +106,3 @@ this.push(element);

}
if (this._bucketLast === this._bucketFirst &&
this._lastInBucket === this._firstInBucket)
if (this._bucketLast === this._bucketFirst && this._lastInBucket === this._firstInBucket)
this._reallocate();

@@ -174,4 +173,3 @@ }

}
if (this._bucketFirst === this._bucketLast &&
this._firstInBucket === this._lastInBucket)
if (this._bucketFirst === this._bucketLast && this._firstInBucket === this._lastInBucket)
this._reallocate();

@@ -775,3 +773,3 @@ }

}
indexInBucket = (overallIndex + 1) % this._bucketSize - 1;
indexInBucket = ((overallIndex + 1) % this._bucketSize) - 1;
if (indexInBucket < 0) {

@@ -778,0 +776,0 @@ indexInBucket = this._bucketSize - 1;

@@ -7,3 +7,3 @@ /**

import type { ElementCallback } from '../../types';
import { IterableElementBase } from "../base";
import { IterableElementBase } from '../base';
import { SinglyLinkedList } from '../linked-list';

@@ -10,0 +10,0 @@ /**

@@ -1,2 +0,2 @@

import { IterableElementBase, IterableEntryBase } from "../../../data-structures";
import { IterableElementBase, IterableEntryBase } from '../../../data-structures';
export type EntryCallback<K, V, R> = (value: V, key: K, index: number, container: IterableEntryBase<K, V>) => R;

@@ -3,0 +3,0 @@ export type ElementCallback<V, R> = (element: V, index: number, container: IterableElementBase<V>) => R;

@@ -1,4 +0,4 @@

import { Comparator } from "../../common";
import { Comparator } from '../../common';
export type HeapOptions<T> = {
comparator: Comparator<T>;
};

@@ -1,2 +0,2 @@

import { HeapOptions } from "../heap";
import { HeapOptions } from '../heap';
export type PriorityQueueOptions<T> = HeapOptions<T> & {};

@@ -25,1 +25,2 @@ /**

export declare const calcMinUnitsRequired: (totalQuantity: number, unitSize: number) => number;
export declare const roundFixed: (num: number, digit?: number) => number;

@@ -12,3 +12,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.calcMinUnitsRequired = exports.isWeakKey = exports.throwRangeError = exports.rangeCheck = exports.getMSB = exports.trampolineAsync = exports.trampoline = exports.toThunk = exports.isThunk = exports.THUNK_SYMBOL = exports.arrayRemove = exports.uuidV4 = void 0;
exports.roundFixed = exports.calcMinUnitsRequired = exports.isWeakKey = exports.throwRangeError = exports.rangeCheck = exports.getMSB = exports.trampolineAsync = exports.trampoline = exports.toThunk = exports.isThunk = exports.THUNK_SYMBOL = exports.arrayRemove = exports.uuidV4 = void 0;
const uuidV4 = function () {

@@ -91,1 +91,6 @@ return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c) {

exports.calcMinUnitsRequired = calcMinUnitsRequired;
const roundFixed = (num, digit = 10) => {
const multiplier = Math.pow(10, digit);
return Math.round(num * multiplier) / multiplier;
};
exports.roundFixed = roundFixed;
{
"name": "heap-typed",
"version": "1.49.4",
"version": "1.49.5",
"description": "Heap. Javascript & Typescript Data Structure.",

@@ -134,4 +134,4 @@ "main": "dist/index.js",

"dependencies": {
"data-structure-typed": "^1.49.4"
"data-structure-typed": "^1.49.5"
}
}

@@ -1,1 +0,1 @@

export * from './iterable-base';
export * from './iterable-base';

@@ -1,5 +0,4 @@

import { ElementCallback, EntryCallback, ReduceElementCallback, ReduceEntryCallback } from "../../types";
import { ElementCallback, EntryCallback, ReduceElementCallback, ReduceEntryCallback } from '../../types';
export abstract class IterableEntryBase<K = any, V = any> {
/**

@@ -150,3 +149,3 @@ * Time Complexity: O(n)

const [key, value] = item;
callbackfn.call(thisArg, value, key, index++, this)
callbackfn.call(thisArg, value, key, index++, this);
}

@@ -180,3 +179,3 @@ }

const [key, value] = item;
accumulator = callbackfn(accumulator, value, key, index++, this)
accumulator = callbackfn(accumulator, value, key, index++, this);
}

@@ -198,3 +197,3 @@ return accumulator;

print(): void {
console.log([...this])
console.log([...this]);
}

@@ -206,3 +205,2 @@

export abstract class IterableElementBase<V> {
/**

@@ -317,3 +315,3 @@ * Time Complexity: O(n)

for (const item of this) {
callbackfn.call(thisArg, item as V, index++, this)
callbackfn.call(thisArg, item as V, index++, this);
}

@@ -343,3 +341,3 @@ }

for (const item of this) {
accumulator = callbackfn(accumulator, item as V, index++, this)
accumulator = callbackfn(accumulator, item as V, index++, this);
}

@@ -349,3 +347,2 @@ return accumulator;

/**

@@ -356,3 +353,3 @@ * Time Complexity: O(n)

print(): void {
console.log([...this])
console.log([...this]);
}

@@ -359,0 +356,0 @@

@@ -21,3 +21,7 @@ /**

export class AVLTreeNode<K = any, V = any, N extends AVLTreeNode<K, V, N> = AVLTreeNodeNested<K, V>> extends BSTNode<K, V, N> {
export class AVLTreeNode<K = any, V = any, N extends AVLTreeNode<K, V, N> = AVLTreeNodeNested<K, V>> extends BSTNode<
K,
V,
N
> {
height: number;

@@ -40,6 +44,10 @@

*/
export class AVLTree<K = any, V = any, N extends AVLTreeNode<K, V, N> = AVLTreeNode<K, V, AVLTreeNodeNested<K, V>>, TREE extends AVLTree<K, V, N, TREE> = AVLTree<K, V, N, AVLTreeNested<K, V, N>>>
export class AVLTree<
K = any,
V = any,
N extends AVLTreeNode<K, V, N> = AVLTreeNode<K, V, AVLTreeNodeNested<K, V>>,
TREE extends AVLTree<K, V, N, TREE> = AVLTree<K, V, N, AVLTreeNested<K, V, N>>
>
extends BST<K, V, N, TREE>
implements IBinaryTree<K, V, N, TREE> {
/**

@@ -82,3 +90,4 @@ * The constructor function initializes an AVLTree object with optional elements and options.

iterationType: this.iterationType,
variant: this.variant, ...options
variant: this.variant,
...options
}) as TREE;

@@ -103,3 +112,3 @@ }

override isNotNodeInstance(potentialKey: BTNKeyOrNode<K, N>): potentialKey is K {
return !(potentialKey instanceof AVLTreeNode)
return !(potentialKey instanceof AVLTreeNode);
}

@@ -112,3 +121,2 @@

/**

@@ -167,3 +175,2 @@ * Time Complexity: O(log n) - logarithmic time, where "n" is the number of nodes in the tree. The add method of the superclass (BST) has logarithmic time complexity.

/**

@@ -498,4 +505,4 @@ * The `_swapProperties` function swaps the key, value, and height properties between two nodes in a binary

return super._replaceNode(oldNode, newNode)
return super._replaceNode(oldNode, newNode);
}
}

@@ -23,3 +23,7 @@ /**

export class BSTNode<K = any, V = any, N extends BSTNode<K, V, N> = BSTNodeNested<K, V>> extends BinaryTreeNode<K, V, N> {
export class BSTNode<K = any, V = any, N extends BSTNode<K, V, N> = BSTNodeNested<K, V>> extends BinaryTreeNode<
K,
V,
N
> {
override parent?: N;

@@ -84,7 +88,10 @@

*/
export class BST<K = any, V = any, N extends BSTNode<K, V, N> = BSTNode<K, V, BSTNodeNested<K, V>>, TREE extends BST<K, V, N, TREE> = BST<K, V, N, BSTNested<K, V, N>>>
export class BST<
K = any,
V = any,
N extends BSTNode<K, V, N> = BSTNode<K, V, BSTNodeNested<K, V>>,
TREE extends BST<K, V, N, TREE> = BST<K, V, N, BSTNested<K, V, N>>
>
extends BinaryTree<K, V, N, TREE>
implements IBinaryTree<K, V, N, TREE> {
/**

@@ -119,3 +126,3 @@ * This is the constructor function for a binary search tree class in TypeScript, which initializes

protected _variant = BSTVariant.MIN
protected _variant = BSTVariant.MIN;

@@ -148,3 +155,4 @@ get variant() {

iterationType: this.iterationType,
variant: this.variant, ...options
variant: this.variant,
...options
}) as TREE;

@@ -162,3 +170,2 @@ }

/**

@@ -309,3 +316,3 @@ * The function `exemplarToNode` takes an exemplar and returns a node if the exemplar is valid,

return !(this.isEntry(kve) && (kve[0] === undefined || kve[0] === null));
}
};

@@ -368,3 +375,2 @@ for (const kve of keysOrNodesOrEntries) {

/**

@@ -408,3 +414,2 @@ * Time Complexity: O(n log n) - Adding each element individually in a balanced tree.

/**

@@ -461,3 +466,3 @@ * Time Complexity: O(log n) - Average case for a balanced tree.

override isNotNodeInstance(potentialKey: BTNKeyOrNode<K, N>): potentialKey is K {
return !(potentialKey instanceof BSTNode)
return !(potentialKey instanceof BSTNode);
}

@@ -750,3 +755,2 @@

protected _setRoot(v: N | undefined) {

@@ -774,3 +778,2 @@ if (v) {

}
}

@@ -24,6 +24,7 @@ /**

export class RedBlackTreeNode<K = any, V = any, N extends RedBlackTreeNode<K, V, N> = RedBlackTreeNodeNested<K, V>> extends BSTNode<
K, V,
N
> {
export class RedBlackTreeNode<
K = any,
V = any,
N extends RedBlackTreeNode<K, V, N> = RedBlackTreeNodeNested<K, V>
> extends BSTNode<K, V, N> {
color: RBTNColor;

@@ -44,3 +45,8 @@

*/
export class RedBlackTree<K = any, V = any, N extends RedBlackTreeNode<K, V, N> = RedBlackTreeNode<K, V, RedBlackTreeNodeNested<K, V>>, TREE extends RedBlackTree<K, V, N, TREE> = RedBlackTree<K, V, N, RedBlackTreeNested<K, V, N>>>
export class RedBlackTree<
K = any,
V = any,
N extends RedBlackTreeNode<K, V, N> = RedBlackTreeNode<K, V, RedBlackTreeNodeNested<K, V>>,
TREE extends RedBlackTree<K, V, N, TREE> = RedBlackTree<K, V, N, RedBlackTreeNested<K, V, N>>
>
extends BST<K, V, N, TREE>

@@ -106,3 +112,4 @@ implements IBinaryTree<K, V, N, TREE> {

iterationType: this.iterationType,
variant: this.variant, ...options
variant: this.variant,
...options
}) as TREE;

@@ -128,3 +135,3 @@ }

override isNotNodeInstance(potentialKey: BTNKeyOrNode<K, N>): potentialKey is K {
return !(potentialKey instanceof RedBlackTreeNode)
return !(potentialKey instanceof RedBlackTreeNode);
}

@@ -198,3 +205,3 @@

if (newNode !== x) {
this._replaceNode(x, newNode)
this._replaceNode(x, newNode);
}

@@ -204,3 +211,2 @@ return;

}
}

@@ -658,4 +664,4 @@

return super._replaceNode(oldNode, newNode)
return super._replaceNode(oldNode, newNode);
}
}

@@ -48,7 +48,10 @@ /**

*/
export class TreeMultimap<K = any, V = any, N extends TreeMultimapNode<K, V, N> = TreeMultimapNode<K, V, TreeMultimapNodeNested<K, V>>,
TREE extends TreeMultimap<K, V, N, TREE> = TreeMultimap<K, V, N, TreeMultimapNested<K, V, N>>>
export class TreeMultimap<
K = any,
V = any,
N extends TreeMultimapNode<K, V, N> = TreeMultimapNode<K, V, TreeMultimapNodeNested<K, V>>,
TREE extends TreeMultimap<K, V, N, TREE> = TreeMultimap<K, V, N, TreeMultimapNested<K, V, N>>
>
extends AVLTree<K, V, N, TREE>
implements IBinaryTree<K, V, N, TREE> {
constructor(elements?: Iterable<BTNExemplar<K, V, N>>, options?: Partial<TreeMultimapOptions<K>>) {

@@ -64,3 +67,3 @@ super([], options);

let sum = 0;
this.subTreeTraverse(node => sum += node.count);
this.subTreeTraverse(node => (sum += node.count));
return sum;

@@ -85,3 +88,4 @@ }

iterationType: this.iterationType,
variant: this.variant, ...options
variant: this.variant,
...options
}) as TREE;

@@ -107,3 +111,3 @@ }

override isNotNodeInstance(potentialKey: BTNKeyOrNode<K, N>): potentialKey is K {
return !(potentialKey instanceof TreeMultimapNode)
return !(potentialKey instanceof TreeMultimapNode);
}

@@ -365,43 +369,2 @@

/**
* Time Complexity: O(1) - constant time, as it performs basic pointer assignments.
* Space Complexity: O(1) - constant space, as it only uses a constant amount of memory.
*
* The function adds a new node to a binary tree, either as the left child or the right child of a
* given parent node.
* @param {N | undefined} newNode - The `newNode` parameter represents the node that needs to be
* added to the binary tree. It can be of type `N` (which represents a node in the binary tree) or
* `undefined` if there is no node to add.
* @param {K | N | undefined} parent - The `parent` parameter represents the parent node to
* which the new node will be added as a child. It can be either a node object (`N`) or a key value
* (`K`).
* @returns The method `_addTo` returns either the `parent.left` or `parent.right` node that was
* added, or `undefined` if no node was added.
*/
protected override _addTo(newNode: N | undefined, parent: BSTNKeyOrNode<K, N>): N | undefined {
parent = this.ensureNode(parent);
if (parent) {
if (parent.left === undefined) {
parent.left = newNode;
if (newNode !== undefined) {
this._size = this.size + 1;
this._count += newNode.count;
}
return parent.left;
} else if (parent.right === undefined) {
parent.right = newNode;
if (newNode !== undefined) {
this._size = this.size + 1;
this._count += newNode.count;
}
return parent.right;
} else {
return;
}
} else {
return;
}
}
/**
* The `_swapProperties` function swaps the key, value, count, and height properties between two nodes.

@@ -441,5 +404,5 @@ * @param {K | N | undefined} srcNode - The `srcNode` parameter represents the source node from

protected _replaceNode(oldNode: N, newNode: N): N {
newNode.count = oldNode.count + newNode.count
newNode.count = oldNode.count + newNode.count;
return super._replaceNode(oldNode, newNode);
}
}

@@ -10,3 +10,3 @@ /**

import { uuidV4 } from '../../utils';
import { IterableEntryBase } from "../base";
import { IterableEntryBase } from '../base';
import { IGraph } from '../../interfaces';

@@ -69,3 +69,5 @@ import { Heap } from '../heap';

EO extends AbstractEdge<E> = AbstractEdge<E>
> extends IterableEntryBase<VertexKey, V | undefined> implements IGraph<V, E, VO, EO> {
>
extends IterableEntryBase<VertexKey, V | undefined>
implements IGraph<V, E, VO, EO> {
constructor() {

@@ -170,3 +172,3 @@ super();

const potentialKeyType = typeof potentialKey;
return potentialKeyType === "string" || potentialKeyType === "number"
return potentialKeyType === 'string' || potentialKeyType === 'number';
}

@@ -668,3 +670,2 @@

): DijkstraResult<VO> {
let minDist = Infinity;

@@ -1177,3 +1178,6 @@ let minDest: VO | undefined = undefined;

if (visited.has(vertex)) {
if ((!isInclude2Cycle && currentPath.length > 2 || isInclude2Cycle && currentPath.length >= 2) && currentPath[0] === vertex.key) {
if (
((!isInclude2Cycle && currentPath.length > 2) || (isInclude2Cycle && currentPath.length >= 2)) &&
currentPath[0] === vertex.key
) {
cycles.push([...currentPath]);

@@ -1203,7 +1207,7 @@ }

for (const cycle of cycles) {
const sorted = [...cycle].sort().toString()
const sorted = [...cycle].sort().toString();
if (uniqueCycles.has(sorted)) continue
if (uniqueCycles.has(sorted)) continue;
else {
uniqueCycles.set(sorted, cycle)
uniqueCycles.set(sorted, cycle);
}

@@ -1213,5 +1217,3 @@ }

// Convert the unique cycles back to an array
return [...uniqueCycles].map(cycleString =>
cycleString[1]
);
return [...uniqueCycles].map(cycleString => cycleString[1]);
}

@@ -1218,0 +1220,0 @@

@@ -185,3 +185,2 @@ /**

/**

@@ -252,3 +251,3 @@ * Time Complexity: O(E) where E is the number of edgeMap

vertex = vertexOrKey;
vertexKey = this._getVertexKey(vertexOrKey)
vertexKey = this._getVertexKey(vertexOrKey);
}

@@ -605,3 +604,2 @@

/**

@@ -608,0 +606,0 @@ * Time Complexity: O(1)

@@ -87,3 +87,8 @@ import type { MapGraphCoordinate, VertexKey } from '../../types';

*/
override createVertex(key: VertexKey, value?: V, lat: number = this.originCoord[0], long: number = this.originCoord[1]): VO {
override createVertex(
key: VertexKey,
value?: V,
lat: number = this.originCoord[0],
long: number = this.originCoord[1]
): VO {
return new MapVertex(key, value, lat, long) as VO;

@@ -90,0 +95,0 @@ }

@@ -165,3 +165,2 @@ /**

/**

@@ -196,3 +195,2 @@ * Time Complexity: O(E), where E is the number of edgeMap incident to the given vertex.

return this.deleteEdgeBetween(oneSide, otherSide);
} else {

@@ -225,6 +223,6 @@ return;

vertex = vertexOrKey;
vertexKey = this._getVertexKey(vertexOrKey)
vertexKey = this._getVertexKey(vertexOrKey);
}
const neighbors = this.getNeighbors(vertexOrKey)
const neighbors = this.getNeighbors(vertexOrKey);

@@ -240,5 +238,4 @@ if (vertex) {

}
})
});
this._edgeMap.delete(vertex);
}

@@ -245,0 +242,0 @@

@@ -30,5 +30,8 @@ /**

*/
constructor(elements: Iterable<[K, V]> = [], options?: {
hashFn: (key: K) => string
}) {
constructor(
elements: Iterable<[K, V]> = [],
options?: {
hashFn: (key: K) => string;
}
) {
super();

@@ -77,3 +80,2 @@ if (options) {

this._objMap.set(key, value);
} else {

@@ -142,3 +144,3 @@ const strKey = this._getNoObjKey(key);

if (this._objMap.has(key)) {
this._size--
this._size--;
}

@@ -241,5 +243,5 @@

protected _isObjKey(key: any): key is (object | ((...args: any[]) => any)) {
protected _isObjKey(key: any): key is object | ((...args: any[]) => any) {
const keyType = typeof key;
return (keyType === 'object' || keyType === 'function') && key !== null
return (keyType === 'object' || keyType === 'function') && key !== null;
}

@@ -251,6 +253,6 @@

let strKey: string;
if (keyType !== "string" && keyType !== "number" && keyType !== "symbol") {
if (keyType !== 'string' && keyType !== 'number' && keyType !== 'symbol') {
strKey = this._hashFn(key);
} else {
if (keyType === "number") {
if (keyType === 'number') {
// TODO numeric key should has its own hash

@@ -272,3 +274,2 @@ strKey = <string>key;

export class LinkedHashMap<K = any, V = any> extends IterableEntryBase<K, V> {
protected _noObjMap: Record<string, HashMapLinkedNode<K, V | undefined>> = {};

@@ -282,8 +283,9 @@ protected _objMap = new WeakMap<object, HashMapLinkedNode<K, V | undefined>>();

constructor(elements?: Iterable<[K, V]>, options: HashMapOptions<K> = {
hashFn: (key: K) => String(key),
objHashFn: (key: K) => (<object>key)
}) {
constructor(
elements?: Iterable<[K, V]>,
options: HashMapOptions<K> = {
hashFn: (key: K) => String(key),
objHashFn: (key: K) => <object>key
}
) {
super();

@@ -290,0 +292,0 @@ this._sentinel = <HashMapLinkedNode<K, V>>{};

@@ -34,9 +34,9 @@ /**

}
}
};
if (options) {
this.options = options
this.options = options;
} else {
this.options = {
comparator: defaultComparator
}
};
}

@@ -229,3 +229,4 @@

const _dfs = (index: number) => {
const left = 2 * index + 1, right = left + 1;
const left = 2 * index + 1,
right = left + 1;
if (index < this.size) {

@@ -385,3 +386,2 @@ if (order === 'in') {

map<T>(callback: ElementCallback<E, T>, comparator: Comparator<T>, thisArg?: any): Heap<T> {
const mappedHeap: Heap<T> = new Heap<T>([], { comparator: comparator });

@@ -438,9 +438,6 @@ let index = 0;

while (index < halfLength) {
let left = index << 1 | 1;
let left = (index << 1) | 1;
const right = left + 1;
let minItem = this.elements[left];
if (
right < this.elements.length &&
this.options.comparator(minItem, this.elements[right]) > 0
) {
if (right < this.elements.length && this.options.comparator(minItem, this.elements[right]) > 0) {
left = right;

@@ -447,0 +444,0 @@ minItem = this.elements[right];

@@ -32,5 +32,6 @@ /**

}
}) {
}
) {
super(elements, options);
}
}

@@ -32,5 +32,6 @@ /**

}
}) {
}
) {
super(elements, options);
}
}

@@ -8,4 +8,4 @@ /**

*/
import type { ElementCallback } from "../../types";
import { IterableElementBase } from "../base";
import type { ElementCallback } from '../../types';
import { IterableElementBase } from '../base';

@@ -719,3 +719,2 @@ export class SinglyLinkedListNode<E = any> {

/**

@@ -722,0 +721,0 @@ * Time Complexity: O(n), where n is the number of elements in the linked list.

export * from './matrix';
export * from './vector2d';
export * from './matrix2d';
export * from './navigator';

@@ -8,21 +8,450 @@ /**

*/
// todo need to be improved
export class MatrixNTI2D<V = any> {
protected readonly _matrix: Array<Array<V>>;
export class Matrix {
/**
* 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:
* The constructor function initializes a matrix object with the provided data and options, or with
* default values if no options are provided.
* @param {number[][]} data - A 2D array of numbers representing the data for the matrix.
* @param [options] - The `options` parameter is an optional object that can contain the following
* properties:
*/
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));
constructor(
data: number[][],
options?: {
rows?: number;
cols?: number;
addFn?: (a: number, b: number) => any;
subtractFn?: (a: number, b: number) => any;
multiplyFn?: (a: number, b: number) => any;
}
) {
if (options) {
const { rows, cols, addFn, subtractFn, multiplyFn } = options;
if (typeof rows === 'number' && rows > 0) this._rows = rows;
else this._rows = data.length;
if (typeof cols === 'number' && cols > 0) this._cols = cols;
else this._cols = data[0]?.length || 0;
if (addFn) this._addFn = addFn;
if (subtractFn) this._subtractFn = subtractFn;
if (multiplyFn) this._multiplyFn = multiplyFn;
} else {
this._rows = data.length;
this._cols = data[0]?.length ?? 0;
}
if (data.length > 0) {
this._data = data;
} else {
this._data = [];
for (let i = 0; i < this.rows; i++) {
this._data[i] = new Array(this.cols).fill(0);
}
}
}
/* The `toArray` method returns the matrix as a two-dimensional array. It converts the internal representation of the
matrix, which is an array of arrays, into a format that is more commonly used in JavaScript. */
toArray(): Array<Array<V>> {
return this._matrix;
protected _rows: number = 0;
get rows(): number {
return this._rows;
}
protected _cols: number = 0;
get cols(): number {
return this._cols;
}
protected _data: number[][];
get data(): number[][] {
return this._data;
}
get addFn() {
return this._addFn;
}
get subtractFn() {
return this._subtractFn;
}
get multiplyFn() {
return this._multiplyFn;
}
/**
* The `get` function returns the value at the specified row and column index if it is a valid index.
* @param {number} row - The `row` parameter represents the row index of the element you want to
* retrieve from the data array.
* @param {number} col - The parameter "col" represents the column number of the element you want to
* retrieve from the data array.
* @returns The `get` function returns a number if the provided row and column indices are valid.
* Otherwise, it returns `undefined`.
*/
get(row: number, col: number): number | undefined {
if (this.isValidIndex(row, col)) {
return this.data[row][col];
}
}
/**
* The set function updates the value at a specified row and column in a two-dimensional array.
* @param {number} row - The "row" parameter represents the row index of the element in a
* two-dimensional array or matrix. It specifies the row where the value will be set.
* @param {number} col - The "col" parameter represents the column index of the element in a
* two-dimensional array.
* @param {number} value - The value parameter represents the number that you want to set at the
* specified row and column in the data array.
* @returns a boolean value. It returns true if the index (row, col) is valid and the value is
* successfully set in the data array. It returns false if the index is invalid and the value is not
* set.
*/
set(row: number, col: number, value: number): boolean {
if (this.isValidIndex(row, col)) {
this.data[row][col] = value;
return true;
}
return false;
}
/**
* The function checks if the dimensions of the given matrix match the dimensions of the current
* matrix.
* @param {Matrix} matrix - The parameter `matrix` is of type `Matrix`.
* @returns a boolean value.
*/
isMatchForCalculate(matrix: Matrix): boolean {
return this.rows === matrix.rows && this.cols === matrix.cols;
}
/**
* The `add` function adds two matrices together, returning a new matrix with the result.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
* @returns The `add` method returns a new `Matrix` object that represents the result of adding the
* current matrix with the provided `matrix` parameter.
*/
add(matrix: Matrix): Matrix | undefined {
if (!this.isMatchForCalculate(matrix)) {
throw new Error('Matrix dimensions must match for addition.');
}
const resultData: number[][] = [];
for (let i = 0; i < this.rows; i++) {
resultData[i] = [];
for (let j = 0; j < this.cols; j++) {
const a = this.get(i, j),
b = matrix.get(i, j);
if (a !== undefined && b !== undefined) {
const added = this._addFn(a, b);
if (added) {
resultData[i][j] = added;
}
}
}
}
return new Matrix(resultData, {
rows: this.rows,
cols: this.cols,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
/**
* The `subtract` function performs element-wise subtraction between two matrices and returns a new
* matrix with the result.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class. It
* represents the matrix that you want to subtract from the current matrix.
* @returns a new Matrix object with the result of the subtraction operation.
*/
subtract(matrix: Matrix): Matrix | undefined {
if (!this.isMatchForCalculate(matrix)) {
throw new Error('Matrix dimensions must match for subtraction.');
}
const resultData: number[][] = [];
for (let i = 0; i < this.rows; i++) {
resultData[i] = [];
for (let j = 0; j < this.cols; j++) {
const a = this.get(i, j),
b = matrix.get(i, j);
if (a !== undefined && b !== undefined) {
const subtracted = this._subtractFn(a, b);
if (subtracted) {
resultData[i][j] = subtracted;
}
}
}
}
return new Matrix(resultData, {
rows: this.rows,
cols: this.cols,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
/**
* The `multiply` function performs matrix multiplication between two matrices and returns the result
* as a new matrix.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
* @returns a new Matrix object.
*/
multiply(matrix: Matrix): Matrix | undefined {
if (this.cols !== matrix.rows) {
throw new Error('Matrix dimensions must be compatible for multiplication (A.cols = B.rows).');
}
const resultData: number[][] = [];
for (let i = 0; i < this.rows; i++) {
resultData[i] = [];
for (let j = 0; j < matrix.cols; j++) {
let sum: number | undefined;
for (let k = 0; k < this.cols; k++) {
const a = this.get(i, k),
b = matrix.get(k, j);
if (a !== undefined && b !== undefined) {
const multiplied = this.multiplyFn(a, b);
if (multiplied !== undefined) {
sum = this.addFn(sum, multiplied);
}
}
}
if (sum !== undefined) resultData[i][j] = sum;
}
}
return new Matrix(resultData, {
rows: this.rows,
cols: matrix.cols,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
/**
* The transpose function takes a matrix and returns a new matrix that is the transpose of the
* original matrix.
* @returns The transpose() function returns a new Matrix object with the transposed data.
*/
transpose(): Matrix {
if (this.data.some(row => row.length !== this.rows)) {
throw new Error('Matrix must be rectangular for transposition.');
}
const resultData: number[][] = [];
for (let j = 0; j < this.cols; j++) {
resultData[j] = [];
for (let i = 0; i < this.rows; i++) {
const trans = this.get(i, j);
if (trans !== undefined) resultData[j][i] = trans;
}
}
return new Matrix(resultData, {
rows: this.cols,
cols: this.rows,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
/**
* The `inverse` function calculates the inverse of a square matrix using Gaussian elimination.
* @returns a Matrix object, which represents the inverse of the original matrix.
*/
inverse(): Matrix | undefined {
// Check if the matrix is square
if (this.rows !== this.cols) {
throw new Error('Matrix must be square for inversion.');
}
// Create an augmented matrix [this | I]
const augmentedMatrixData: number[][] = [];
for (let i = 0; i < this.rows; i++) {
augmentedMatrixData[i] = this.data[i].slice(); // Copy the original matrix
for (let j = 0; j < this.cols; j++) {
augmentedMatrixData[i][this.cols + j] = i === j ? 1 : 0; // Append the identity matrix
}
}
const augmentedMatrix = new Matrix(augmentedMatrixData, {
rows: this.rows,
cols: this.cols * 2,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
// Apply Gaussian elimination to transform the left half into the identity matrix
for (let i = 0; i < this.rows; i++) {
// Find pivot
let pivotRow = i;
while (pivotRow < this.rows && augmentedMatrix.get(pivotRow, i) === 0) {
pivotRow++;
}
if (pivotRow === this.rows) {
// Matrix is singular, and its inverse does not exist
throw new Error('Matrix is singular, and its inverse does not exist.');
}
// Swap rows to make the pivot the current row
augmentedMatrix._swapRows(i, pivotRow);
// Scale the pivot row to make the pivot element 1
const pivotElement = augmentedMatrix.get(i, i) ?? 1;
if (pivotElement === 0) {
// Handle division by zero
throw new Error('Matrix is singular, and its inverse does not exist (division by zero).');
}
augmentedMatrix._scaleRow(i, 1 / pivotElement);
// Eliminate other rows to make elements in the current column zero
for (let j = 0; j < this.rows; j++) {
if (j !== i) {
let factor = augmentedMatrix.get(j, i);
if (factor === undefined) factor = 0;
augmentedMatrix._addScaledRow(j, i, -factor);
}
}
}
// Extract the right half of the augmented matrix as the inverse
const inverseData: number[][] = [];
for (let i = 0; i < this.rows; i++) {
inverseData[i] = augmentedMatrix.data[i].slice(this.cols);
}
return new Matrix(inverseData, {
rows: this.rows,
cols: this.cols,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
/**
* The dot function calculates the dot product of two matrices and returns a new matrix.
* @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
* @returns a new Matrix object.
*/
dot(matrix: Matrix): Matrix | undefined {
if (this.cols !== matrix.rows) {
throw new Error(
'Number of columns in the first matrix must be equal to the number of rows in the second matrix for dot product.'
);
}
const resultData: number[][] = [];
for (let i = 0; i < this.rows; i++) {
resultData[i] = [];
for (let j = 0; j < matrix.cols; j++) {
let sum: number | undefined;
for (let k = 0; k < this.cols; k++) {
const a = this.get(i, k),
b = matrix.get(k, j);
if (a !== undefined && b !== undefined) {
const multiplied = this.multiplyFn(a, b);
if (multiplied !== undefined) {
sum = this.addFn(sum, multiplied);
}
}
}
if (sum !== undefined) resultData[i][j] = sum;
}
}
return new Matrix(resultData, {
rows: this.rows,
cols: matrix.cols,
addFn: this.addFn,
subtractFn: this.subtractFn,
multiplyFn: this.multiplyFn
});
}
protected _addFn(a: number | undefined, b: number): number | undefined {
if (a === undefined) return b;
return a + b;
}
protected _subtractFn(a: number, b: number) {
return a - b;
}
protected _multiplyFn(a: number, b: number) {
return a * b;
}
/**
* The function checks if a given row and column index is valid within a specified range.
* @param {number} row - The `row` parameter represents the row index of a two-dimensional array or
* matrix. It is a number that indicates the specific row in the matrix.
* @param {number} col - The "col" parameter represents the column index in a two-dimensional array
* or grid. It is used to check if the given column index is valid within the bounds of the grid.
* @returns A boolean value is being returned.
*/
protected isValidIndex(row: number, col: number): boolean {
return row >= 0 && row < this.rows && col >= 0 && col < this.cols;
}
/**
* The function `_swapRows` swaps the positions of two rows in an array.
* @param {number} row1 - The `row1` parameter is the index of the first row that you want to swap.
* @param {number} row2 - The `row2` parameter is the index of the second row that you want to swap
* with the first row.
*/
protected _swapRows(row1: number, row2: number): void {
const temp = this.data[row1];
this.data[row1] = this.data[row2];
this.data[row2] = temp;
}
/**
* The function scales a specific row in a matrix by a given scalar value.
* @param {number} row - The `row` parameter represents the index of the row in the matrix that you
* want to scale. It is a number that indicates the position of the row within the matrix.
* @param {number} scalar - The scalar parameter is a number that is used to multiply each element in
* a specific row of a matrix.
*/
protected _scaleRow(row: number, scalar: number): void {
for (let j = 0; j < this.cols; j++) {
let multiplied = this.multiplyFn(this.data[row][j], scalar);
if (multiplied === undefined) multiplied = 0;
this.data[row][j] = multiplied;
}
}
/**
* The function `_addScaledRow` multiplies a row in a matrix by a scalar value and adds it to another
* row.
* @param {number} targetRow - The targetRow parameter represents the index of the row in which the
* scaled values will be added.
* @param {number} sourceRow - The sourceRow parameter represents the index of the row from which the
* values will be scaled and added to the targetRow.
* @param {number} scalar - The scalar parameter is a number that is used to scale the values in the
* source row before adding them to the target row.
*/
protected _addScaledRow(targetRow: number, sourceRow: number, scalar: number): void {
for (let j = 0; j < this.cols; j++) {
let multiplied = this.multiplyFn(this.data[sourceRow][j], scalar);
if (multiplied === undefined) multiplied = 0;
const scaledValue = multiplied;
let added = this.addFn(this.data[targetRow][j], scaledValue);
if (added === undefined) added = 0;
this.data[targetRow][j] = added;
}
}
}

@@ -12,12 +12,13 @@ /**

export class MinPriorityQueue<E = any> extends PriorityQueue<E> {
constructor(elements?: Iterable<E>,
options: PriorityQueueOptions<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');
} else {
return a - b;
}
}
}
constructor(
elements?: Iterable<E>,
options: PriorityQueueOptions<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');
} else {
return a - b;
}
}
}
) {

@@ -24,0 +25,0 @@ super(elements, options);

@@ -8,5 +8,5 @@ /**

*/
import type { ElementCallback, IterableWithSizeOrLength } from "../../types";
import { IterableElementBase } from "../base";
import { calcMinUnitsRequired, rangeCheck } from "../../utils";
import type { ElementCallback, IterableWithSizeOrLength } from '../../types';
import { IterableElementBase } from '../base';
import { calcMinUnitsRequired, rangeCheck } from '../../utils';

@@ -37,9 +37,11 @@ /**

*/
constructor(elements: IterableWithSizeOrLength<E> = [], bucketSize = (1 << 12)) {
constructor(elements: IterableWithSizeOrLength<E> = [], bucketSize = 1 << 12) {
super();
let _size: number;
if ('length' in elements) {
if (elements.length instanceof Function) _size = elements.length(); else _size = elements.length;
if (elements.length instanceof Function) _size = elements.length();
else _size = elements.length;
} else {
if (elements.size instanceof Function) _size = elements.size(); else _size = elements.size;
if (elements.size instanceof Function) _size = elements.size();
else _size = elements.size;
}

@@ -54,3 +56,3 @@

this._bucketFirst = this._bucketLast = (this._bucketCount >> 1) - (needBucketNum >> 1);
this._firstInBucket = this._lastInBucket = (this._bucketSize - _size % this._bucketSize) >> 1;
this._firstInBucket = this._lastInBucket = (this._bucketSize - (_size % this._bucketSize)) >> 1;

@@ -114,6 +116,3 @@ for (const element of elements) {

}
if (
this._bucketLast === this._bucketFirst &&
this._lastInBucket === this._firstInBucket
) this._reallocate();
if (this._bucketLast === this._bucketFirst && this._lastInBucket === this._firstInBucket) this._reallocate();
}

@@ -182,6 +181,3 @@ this._size += 1;

}
if (
this._bucketFirst === this._bucketLast &&
this._firstInBucket === this._lastInBucket
) this._reallocate();
if (this._bucketFirst === this._bucketLast && this._firstInBucket === this._lastInBucket) this._reallocate();
}

@@ -268,3 +264,2 @@ this._size += 1;

/**

@@ -287,10 +282,6 @@ * Time Complexity: O(1)

rangeCheck(pos, 0, this.size - 1);
const {
bucketIndex,
indexInBucket
} = this._getBucketAndPosition(pos);
const { bucketIndex, indexInBucket } = this._getBucketAndPosition(pos);
return this._buckets[bucketIndex][indexInBucket]!;
}
/**

@@ -313,6 +304,3 @@ * Time Complexity: O(1)

rangeCheck(pos, 0, this.size - 1);
const {
bucketIndex,
indexInBucket
} = this._getBucketAndPosition(pos);
const { bucketIndex, indexInBucket } = this._getBucketAndPosition(pos);
this._buckets[bucketIndex][indexInBucket] = element;

@@ -381,6 +369,3 @@ return true;

}
const {
bucketIndex,
indexInBucket
} = this._getBucketAndPosition(pos);
const { bucketIndex, indexInBucket } = this._getBucketAndPosition(pos);
this._bucketLast = bucketIndex;

@@ -414,11 +399,5 @@ this._lastInBucket = indexInBucket;

const length = this.size - 1;
let {
bucketIndex: curBucket,
indexInBucket: curPointer
} = this._getBucketAndPosition(pos);
let { bucketIndex: curBucket, indexInBucket: curPointer } = this._getBucketAndPosition(pos);
for (let i = pos; i < length; ++i) {
const {
bucketIndex: nextBucket,
indexInBucket: nextPointer
} = this._getBucketAndPosition(pos + 1);
const { bucketIndex: nextBucket, indexInBucket: nextPointer } = this._getBucketAndPosition(pos + 1);
this._buckets[curBucket][curPointer] = this._buckets[nextBucket][nextPointer];

@@ -840,3 +819,3 @@ curBucket = nextBucket;

indexInBucket = (overallIndex + 1) % this._bucketSize - 1;
indexInBucket = ((overallIndex + 1) % this._bucketSize) - 1;
if (indexInBucket < 0) {

@@ -848,2 +827,2 @@ indexInBucket = this._bucketSize - 1;

}
}
}

@@ -7,3 +7,3 @@ /**

import type { ElementCallback } from '../../types';
import { IterableElementBase } from "../base";
import { IterableElementBase } from '../base';
import { SinglyLinkedList } from '../linked-list';

@@ -10,0 +10,0 @@

@@ -8,6 +8,11 @@ import { BinaryTree, BinaryTreeNode } from '../data-structures';

BTNCallback,
BTNExemplar,
BTNExemplar
} from '../types';
export interface IBinaryTree<K = number, V = any, N extends BinaryTreeNode<K, V, N> = BinaryTreeNodeNested<K, V>, TREE extends BinaryTree<K, V, N, TREE> = BinaryTreeNested<K, V, N>> {
export interface IBinaryTree<
K = number,
V = any,
N extends BinaryTreeNode<K, V, N> = BinaryTreeNodeNested<K, V>,
TREE extends BinaryTree<K, V, N, TREE> = BinaryTreeNested<K, V, N>
> {
createNode(key: K, value?: N['value']): N;

@@ -14,0 +19,0 @@

export enum BSTVariant {
MIN = 'MIN',
MAX = 'MAX',
MAX = 'MAX'
}

@@ -49,5 +49,5 @@

export type IterableWithSizeOrLength<T> = IterableWithSize<T> | IterableWithLength<T>
export type IterableWithSizeOrLength<T> = IterableWithSize<T> | IterableWithLength<T>;
export type BinaryTreePrintOptions = { isShowUndefined?: boolean, isShowNull?: boolean, isShowRedBlackNIL?: boolean }
export type BinaryTreePrintOptions = { isShowUndefined?: boolean; isShowNull?: boolean; isShowRedBlackNIL?: boolean };

@@ -58,3 +58,3 @@ export type BTNEntry<K, V> = [K | null | undefined, V | undefined];

export type BTNExemplar<K, V, N> = BTNEntry<K, V> | BTNKeyOrNode<K, N>
export type BTNExemplar<K, V, N> = BTNEntry<K, V> | BTNKeyOrNode<K, N>;

@@ -61,0 +61,0 @@ export type BTNodePureKeyOrNode<K, N> = K | N;

@@ -1,6 +0,17 @@

import { IterableElementBase, IterableEntryBase } from "../../../data-structures";
import { IterableElementBase, IterableEntryBase } from '../../../data-structures';
export type EntryCallback<K, V, R> = (value: V, key: K, index: number, container: IterableEntryBase<K, V>) => R;
export type ElementCallback<V, R> = (element: V, index: number, container: IterableElementBase<V>) => R;
export type ReduceEntryCallback<K, V, R> = (accumulator: R, value: V, key: K, index: number, container: IterableEntryBase<K, V>) => R;
export type ReduceElementCallback<V, R> = (accumulator: R, element: V, index: number, container: IterableElementBase<V>) => R;
export type ReduceEntryCallback<K, V, R> = (
accumulator: R,
value: V,
key: K,
index: number,
container: IterableEntryBase<K, V>
) => R;
export type ReduceElementCallback<V, R> = (
accumulator: R,
element: V,
index: number,
container: IterableElementBase<V>
) => R;

@@ -1,1 +0,1 @@

export * from './base';
export * from './base';
export type VertexKey = string | number;
export type DijkstraResult<V> = {
export type DijkstraResult<V> =
| {
distMap: Map<V, number>;

@@ -11,2 +12,3 @@ distPaths?: Map<V, V[]>;

minPath: V[];
} | undefined;
}
| undefined;

@@ -10,5 +10,5 @@ export type HashMapLinkedNode<K, V> = {

hashFn: (key: K) => string;
objHashFn: (key: K) => object
}
objHashFn: (key: K) => object;
};
export type HashMapStoreItem<K, V> = { key: K, value: V };
export type HashMapStoreItem<K, V> = { key: K; value: V };

@@ -1,3 +0,3 @@

import { Comparator } from "../../common";
import { Comparator } from '../../common';
export type HeapOptions<T> = { comparator: Comparator<T> }
export type HeapOptions<T> = { comparator: Comparator<T> };

@@ -1,3 +0,3 @@

import { HeapOptions } from "../heap";
import { HeapOptions } from '../heap';
export type PriorityQueueOptions<T> = HeapOptions<T> & {}
export type PriorityQueueOptions<T> = HeapOptions<T> & {};

@@ -101,2 +101,8 @@ /**

export const calcMinUnitsRequired = (totalQuantity: number, unitSize: number) => Math.floor((totalQuantity + unitSize - 1) / unitSize)
export const calcMinUnitsRequired = (totalQuantity: number, unitSize: number) =>
Math.floor((totalQuantity + unitSize - 1) / unitSize);
export const roundFixed = (num: number, digit: number = 10) => {
const multiplier = Math.pow(10, digit);
return Math.round(num * multiplier) / multiplier;
};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc