Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ts-structures

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-structures - npm Package Compare versions

Comparing version 0.5.2 to 0.5.3

14

_shared/capped-structure.d.ts

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

/**
* A CappedStructure has a `length` and a `capacity`, allowing it to use
* the `guardOverflow` decorator on insertion methods to prevent overflow.
*/
interface CappedStructure {

@@ -5,4 +9,14 @@ length: number;

}
/**
* Method decorator that prevents a structure from overflowing. The structure
* must implement CappedStructure interface. In case of overflow, it throws
* an error if `throwError` parameter is set to `true`, or returns the
* specified `returnValue` otherwise.
*
* @param throwError - Whether it should throw an error or not in case of overflow
* @param returnValue - The value to be returned in case of overflow, if `throwError`
* is set to `false` (it is ignored otherwise)
*/
declare function guardOverflow(throwError: boolean, returnValue?: any): (target: Object, methodName: string, descriptor: PropertyDescriptor) => void;
export default CappedStructure;
export { guardOverflow, };

16

_shared/capped-structure.js

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

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.guardOverflow = void 0;
/**
* Method decorator that prevents a structure from overflowing. The structure
* must implement CappedStructure interface. In case of overflow, it throws
* an error if `throwError` parameter is set to `true`, or returns the
* specified `returnValue` otherwise.
*
* @param throwError - Whether it should throw an error or not in case of overflow
* @param returnValue - The value to be returned in case of overflow, if `throwError`
* is set to `false` (it is ignored otherwise)
*/
function guardOverflow(throwError, returnValue) {

@@ -15,3 +28,2 @@ return (target, methodName, descriptor) => {

}
export { guardOverflow, };
//# sourceMappingURL=capped-structure.js.map
exports.guardOverflow = guardOverflow;

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

/**
* A function that compares two elements a and b of the same type.
* It can be applied to any data type, including arrays or objects.
* It should return `-1` if a considered inferior to b, `1` if superior,
* and `zero` if considered equals.
*/
declare type CompareFunction<T> = (a: T, b: T) => -1 | 0 | 1;

@@ -11,7 +17,56 @@ interface Comparer<T> {

}
/**
* The function used to compare two elements in an ordered data structure.
* By default, it compares numbers so it must be replaced with a custom
* function (via `setCompareFunction`) when storing another data type.
*
* @param a - Element a
* @param b - Element b
* @returns `-1` if a \< b, `1` if a \> b, `0` if a === b
*/
declare function compare<T>(a: T, b: T): -1 | 0 | 1;
/**
* Returns `true` if a and b are equal, `false` otherwise.
*
* @param this- The hosting structure
* @param a - Element a
* @param b - Element b
* @returns `true` / `false`
*/
declare function equal<T>(this: any, a: T, b: T): boolean;
/**
* Returns `true` if a is inferior to b, `false` otherwise.
*
* @param this- The hosting structure
* @param a - Element a
* @param b - Element b
* @returns `true` / `false`
*/
declare function inf<T>(this: any, a: T, b: T): boolean;
/**
* Returns `true` if a is superior to b, `false` otherwise.
*
* @param this- The hosting structure
* @param a - Element a
* @param b - Element b
* @returns `true` / `false`
*/
declare function sup<T>(this: any, a: T, b: T): boolean;
/**
* Returns `true` if a is inferior or equal to b, `false` otherwise.
*
* @param this- The hosting structure
* @param a - Element a
* @param b - Element b
* @returns `true` / `false`
*/
declare function infOrEqual<T>(this: any, a: T, b: T): boolean;
/**
* Returns `true` if a is superior or equal to b, `false` otherwise.
*
* @param this- The hosting structure
* @param a - Element a
* @param b - Element b
* @returns `true` / `false`
*/
declare function supOrEqual<T>(this: any, a: T, b: T): boolean;

@@ -18,0 +73,0 @@ declare const compareMethods: {

@@ -0,13 +1,57 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compareMethods = void 0;
/**
* The function used to compare two elements in an ordered data structure.
* By default, it compares numbers so it must be replaced with a custom
* function (via `setCompareFunction`) when storing another data type.
*
* @param a - Element a
* @param b - Element b
* @returns `-1` if a \< b, `1` if a \> b, `0` if a === b
*/
function compare(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
/**
* Returns `true` if a and b are equal, `false` otherwise.
*
* @param this- The hosting structure
* @param a - Element a
* @param b - Element b
* @returns `true` / `false`
*/
function equal(a, b) {
return this.compare(a, b) === 0;
}
/**
* Returns `true` if a is inferior to b, `false` otherwise.
*
* @param this- The hosting structure
* @param a - Element a
* @param b - Element b
* @returns `true` / `false`
*/
function inf(a, b) {
return this.compare(a, b) === -1;
}
/**
* Returns `true` if a is superior to b, `false` otherwise.
*
* @param this- The hosting structure
* @param a - Element a
* @param b - Element b
* @returns `true` / `false`
*/
function sup(a, b) {
return this.compare(a, b) === 1;
}
/**
* Returns `true` if a is inferior or equal to b, `false` otherwise.
*
* @param this- The hosting structure
* @param a - Element a
* @param b - Element b
* @returns `true` / `false`
*/
function infOrEqual(a, b) {

@@ -17,2 +61,10 @@ const value = this.compare(a, b);

}
/**
* Returns `true` if a is superior or equal to b, `false` otherwise.
*
* @param this- The hosting structure
* @param a - Element a
* @param b - Element b
* @returns `true` / `false`
*/
function supOrEqual(a, b) {

@@ -30,3 +82,2 @@ const value = this.compare(a, b);

};
export { compareMethods, };
//# sourceMappingURL=comparer.js.map
exports.compareMethods = compareMethods;

14

_shared/index.js

@@ -1,5 +0,9 @@

import { compareMethods, } from './comparer';
import { TraverseMethod, } from './types';
import { guardOverflow, } from './capped-structure';
export { compareMethods, guardOverflow, TraverseMethod, };
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraverseMethod = exports.guardOverflow = exports.compareMethods = void 0;
const comparer_1 = require("./comparer");
Object.defineProperty(exports, "compareMethods", { enumerable: true, get: function () { return comparer_1.compareMethods; } });
const types_1 = require("./types");
Object.defineProperty(exports, "TraverseMethod", { enumerable: true, get: function () { return types_1.TraverseMethod; } });
const capped_structure_1 = require("./capped-structure");
Object.defineProperty(exports, "guardOverflow", { enumerable: true, get: function () { return capped_structure_1.guardOverflow; } });

@@ -0,9 +1,54 @@

/**
* A callback function used in a structure traversal. It takes the current
* value as input and returns a boolean describing whether or not the value
* should be present in the filtered structure.
*/
declare type FilterFunction<T> = (currentValue: T) => boolean;
/**
* A callback function used in a structure traversal. It takes the current
* value as input and returns a new value that will replace the current
* one in the mapped structure.
*/
declare type MapFunction<T, U> = (currentValue: T) => U;
/**
* A callback function used in a structure traversal. It takes an accumulator
* and the current value as input and returns a value that will be the
* accumulator for the next value. The final result will be the last
* accumulator value at the end of traversaL.
*/
declare type ReduceFunction<T, U> = (accumulator: U, currentValue: T) => U;
/**
* A function called on each value encountered during a tree traversal.
*/
declare type TraverseCallback<T> = (currentValue: T) => any;
/**
* Methods of traversal of a tree or graph. Used in structures methods
* that require traversal when the order matters.
* Usage example:
*
* `myTree.toArray(TraverseMethod.DFSPreOrder)` -\> [0, -10, 10]
*
* `myTree.toArray(TraverseMethod.DFSInOrder)` -\> [-10, 0, 10]
*/
declare enum TraverseMethod {
/**
* Breadth First Search: traverses all values of the same level of depth,
* from left to right, before moving to the next level.
*/
BFS = 0,
/**
* Depth First Search PreOrder: for each node, traverses the current value
* first, then its children from left to right.
*/
DFSPreOrder = 1,
/**
* Depth First Search InOrder: for each node, traverses the left child
* first, then the current value and the right child. This results in
* a traversal in ascending order.
*/
DFSInOrder = 2,
/**
* Depth First Search PostOrder: for each node, traverses its children first
* from left to right, then the current value.
*/
DFSPostOrder = 3

@@ -10,0 +55,0 @@ }

@@ -0,9 +1,37 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraverseMethod = void 0;
/**
* Methods of traversal of a tree or graph. Used in structures methods
* that require traversal when the order matters.
* Usage example:
*
* `myTree.toArray(TraverseMethod.DFSPreOrder)` -\> [0, -10, 10]
*
* `myTree.toArray(TraverseMethod.DFSInOrder)` -\> [-10, 0, 10]
*/
var TraverseMethod;
(function (TraverseMethod) {
/**
* Breadth First Search: traverses all values of the same level of depth,
* from left to right, before moving to the next level.
*/
TraverseMethod[TraverseMethod["BFS"] = 0] = "BFS";
/**
* Depth First Search PreOrder: for each node, traverses the current value
* first, then its children from left to right.
*/
TraverseMethod[TraverseMethod["DFSPreOrder"] = 1] = "DFSPreOrder";
/**
* Depth First Search InOrder: for each node, traverses the left child
* first, then the current value and the right child. This results in
* a traversal in ascending order.
*/
TraverseMethod[TraverseMethod["DFSInOrder"] = 2] = "DFSInOrder";
/**
* Depth First Search PostOrder: for each node, traverses its children first
* from left to right, then the current value.
*/
TraverseMethod[TraverseMethod["DFSPostOrder"] = 3] = "DFSPostOrder";
})(TraverseMethod || (TraverseMethod = {}));
export { TraverseMethod, };
//# sourceMappingURL=types.js.map
exports.TraverseMethod = TraverseMethod;

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

import ListGraph from './list-graph';
import { ListGraph } from './list-graph';
interface Graph<T extends number | string> {

@@ -3,0 +3,0 @@ get(vertex: Vertex<T>): EdgeSet | undefined;

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

import ListGraph from './list-graph';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EdgeSet = exports.Edge = exports.ListGraph = void 0;
const list_graph_1 = require("./list-graph");
Object.defineProperty(exports, "ListGraph", { enumerable: true, get: function () { return list_graph_1.ListGraph; } });
class Edge {

@@ -12,2 +16,4 @@ constructor(vertex, weight) {

}
exports.Edge = Edge;
// Todo: change set to map?
class EdgeSet extends Set {

@@ -32,3 +38,2 @@ hasVertex(vertex) {

}
export { ListGraph, Edge, EdgeSet, };
//# sourceMappingURL=index.js.map
exports.EdgeSet = EdgeSet;

@@ -18,2 +18,2 @@ import type { Vertex } from '.';

}
export default ListGraph;
export { ListGraph };

@@ -1,5 +0,23 @@

import { EdgeSet, Edge, } from '.';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ListGraph = void 0;
const _1 = require(".");
class ListGraph {
constructor() {
this.data = new Map();
// public traverseDFSRecursive(
// start: Vertex<string>,
// callback: TraverseCallback<Vertex<string>>,
// ) {
// const visited = new Set<Vertex<string>>()
// const recurse = (current: Vertex<string>) => {
// if (!current) return
// callback(current)
// visited.add(current)
// this.get(current)!.forEach((edge: Edge) => {
// if (!visited.has(edge.vertex)) return recurse(edge.vertex)
// })
// }
// recurse(start)
// }
}

@@ -19,3 +37,3 @@ get size() {

return false;
this.data.set(vertex, new EdgeSet());
this.data.set(vertex, new _1.EdgeSet());
return true;

@@ -33,2 +51,5 @@ }

}
// TODO: reconsider behaviour when one of the two directions already exists.
// Let's not forget the weight: should it be replaced in such case?
// Maybe just block any addition as soon as a connection exists.
addEdge(vertexA, vertexB, weight = 1) {

@@ -49,3 +70,3 @@ const edgeAddedA = this.addDirectedEdge(vertexA, vertexB, weight);

return false;
return !!srcEdges.add(new Edge(to, weight));
return !!srcEdges.add(new _1.Edge(to, weight));
}

@@ -68,3 +89,2 @@ removeDirectedEdge(from, to) {

}
export default ListGraph;
//# sourceMappingURL=list-graph.js.map
exports.ListGraph = ListGraph;
import type { Comparer, CompareFunction } from '../_shared';
/**
* Implementation of a Binary Heap that behaves like a max binary heap
* with numeric values by default. Nevertheless, it can be provided
* a custom `CompareFunction` to store any type of data, or to
* use it as a min binary heap for instance.
*/
declare class BinaryHeap<T> implements Comparer<T> {
private values;
/**
* The function used to compare two elements.
* It is determinant for the heap structure.
* By default, it compares numbers so it must be replaced with a custom
* function when storing another data type.
* It also allows to use a MinBinaryHeap
*
* @param a - Element A
* @param b - Element B
* @returns `-1` if a \< b, `1` if a \> b, `0` if a === b
*/
compare: CompareFunction<T>;

@@ -10,2 +27,12 @@ inf: <T_1>(this: any, a: T_1, b: T_1) => boolean;

supOrEqual: <T_1>(this: any, a: T_1, b: T_1) => boolean;
/**
* Replaces the current compare function with the provided
* `CompareFunction`. A compare function has the signature:
* `CompareFunction<T>(a: T, b: T) => -1 | 0 | 1`.
*
* To keep its integrity, the tree is fully rebuilt.
*
* @param compareFunction - The function to use to compare two values.
* @returns The tree instance.
*/
setCompareFunction(compareFunction: CompareFunction<T>): BinaryHeap<T>;

@@ -22,2 +49,2 @@ get length(): number;

}
export default BinaryHeap;
export { BinaryHeap };

@@ -1,14 +0,45 @@

import { compareMethods, } from '../_shared';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinaryHeap = void 0;
const _shared_1 = require("../_shared");
/**
* Implementation of a Binary Heap that behaves like a max binary heap
* with numeric values by default. Nevertheless, it can be provided
* a custom `CompareFunction` to store any type of data, or to
* use it as a min binary heap for instance.
*/
class BinaryHeap {
constructor() {
this.values = [];
this.compare = compareMethods.compare.bind(this);
this.inf = compareMethods.inf.bind(this);
this.sup = compareMethods.sup.bind(this);
this.equal = compareMethods.equal.bind(this);
this.infOrEqual = compareMethods.infOrEqual.bind(this);
this.supOrEqual = compareMethods.supOrEqual.bind(this);
/**
* The function used to compare two elements.
* It is determinant for the heap structure.
* By default, it compares numbers so it must be replaced with a custom
* function when storing another data type.
* It also allows to use a MinBinaryHeap
*
* @param a - Element A
* @param b - Element B
* @returns `-1` if a \< b, `1` if a \> b, `0` if a === b
*/
this.compare = _shared_1.compareMethods.compare.bind(this);
this.inf = _shared_1.compareMethods.inf.bind(this);
this.sup = _shared_1.compareMethods.sup.bind(this);
this.equal = _shared_1.compareMethods.equal.bind(this);
this.infOrEqual = _shared_1.compareMethods.infOrEqual.bind(this);
this.supOrEqual = _shared_1.compareMethods.supOrEqual.bind(this);
}
/**
* Replaces the current compare function with the provided
* `CompareFunction`. A compare function has the signature:
* `CompareFunction<T>(a: T, b: T) => -1 | 0 | 1`.
*
* To keep its integrity, the tree is fully rebuilt.
*
* @param compareFunction - The function to use to compare two values.
* @returns The tree instance.
*/
setCompareFunction(compareFunction) {
this.compare = compareFunction;
// rebuild heap according to the new compare function
const values = this.toArray();

@@ -90,3 +121,2 @@ this.clear();

}
export default BinaryHeap;
//# sourceMappingURL=binary-heap.js.map
exports.BinaryHeap = BinaryHeap;

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

import BinaryHeap from './binary-heap';
import { BinaryHeap } from './binary-heap';
export { BinaryHeap, };

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

import BinaryHeap from './binary-heap';
export { BinaryHeap, };
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinaryHeap = void 0;
const binary_heap_1 = require("./binary-heap");
Object.defineProperty(exports, "BinaryHeap", { enumerable: true, get: function () { return binary_heap_1.BinaryHeap; } });

@@ -1,9 +0,18 @@

import { TraverseMethod } from './_shared';
import { DoublyLinkedList } from './list';
import { Queue, PriorityQueue, } from './queue';
import { Stack } from './stack';
import { BinarySearchTree } from './tree';
import { BinaryHeap } from './heap';
import { ListGraph } from './graph';
export { DoublyLinkedList, Queue, PriorityQueue, Stack, BinarySearchTree, TraverseMethod, BinaryHeap, ListGraph, };
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ListGraph = exports.BinaryHeap = exports.TraverseMethod = exports.BinarySearchTree = exports.Stack = exports.PriorityQueue = exports.Queue = exports.DoublyLinkedList = void 0;
const _shared_1 = require("./_shared");
Object.defineProperty(exports, "TraverseMethod", { enumerable: true, get: function () { return _shared_1.TraverseMethod; } });
const list_1 = require("./list");
Object.defineProperty(exports, "DoublyLinkedList", { enumerable: true, get: function () { return list_1.DoublyLinkedList; } });
const queue_1 = require("./queue");
Object.defineProperty(exports, "Queue", { enumerable: true, get: function () { return queue_1.Queue; } });
Object.defineProperty(exports, "PriorityQueue", { enumerable: true, get: function () { return queue_1.PriorityQueue; } });
const stack_1 = require("./stack");
Object.defineProperty(exports, "Stack", { enumerable: true, get: function () { return stack_1.Stack; } });
const tree_1 = require("./tree");
Object.defineProperty(exports, "BinarySearchTree", { enumerable: true, get: function () { return tree_1.BinarySearchTree; } });
const heap_1 = require("./heap");
Object.defineProperty(exports, "BinaryHeap", { enumerable: true, get: function () { return heap_1.BinaryHeap; } });
const graph_1 = require("./graph");
Object.defineProperty(exports, "ListGraph", { enumerable: true, get: function () { return graph_1.ListGraph; } });
import type { List, ListNode, ListMapper, ListFilterer, ListReducer } from './';
declare type DLLNode<T> = DoublyLinkedListNode<T>;
/**
* DoublyLinkedListNode carries a value and keeps reference of the
* previous and the next node. It also stores a reference to the `List`
* it belongs to for checking purposes.
*/
declare class DoublyLinkedListNode<T> implements ListNode<T> {

@@ -10,2 +15,6 @@ value: T;

}
/**
* Doubly Linked List implementation with basic operations. It also features
* some higher order methods, such as `map` `filter` `reduce`.
*/
declare class DoublyLinkedList<T> implements List<T> {

@@ -31,2 +40,2 @@ length: number;

}
export default DoublyLinkedList;
export { DoublyLinkedList };

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

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DoublyLinkedList = void 0;
/**
* DoublyLinkedListNode carries a value and keeps reference of the
* previous and the next node. It also stores a reference to the `List`
* it belongs to for checking purposes.
*/
class DoublyLinkedListNode {

@@ -9,2 +17,6 @@ constructor(list, value, prev, next) {

}
/**
* Doubly Linked List implementation with basic operations. It also features
* some higher order methods, such as `map` `filter` `reduce`.
*/
class DoublyLinkedList {

@@ -100,3 +112,2 @@ constructor() {

}
export default DoublyLinkedList;
//# sourceMappingURL=doubly-linked-list.js.map
exports.DoublyLinkedList = DoublyLinkedList;

@@ -1,5 +0,8 @@

import DoublyLinkedList from './doubly-linked-list';
import { DoublyLinkedList } from './doubly-linked-list';
declare type ListMapper<T, U> = (currentValue: T, currentNode?: ListNode<T>, currentList?: List<T>) => U;
declare type ListFilterer<T> = (currentValue: T, currentNode?: ListNode<T>, currentList?: List<T>) => boolean;
declare type ListReducer<T, U> = (accumulator: U, currentValue: T) => U;
/**
* Represents an element of a `List`.
*/
interface ListNode<T> {

@@ -10,15 +13,89 @@ value: T;

}
/**
* Represents a linked list, that can be a `SinglyLinkedList`
* or a `DoublyLinkedList`.
*/
interface List<T> {
/**
* Adds a `ListNode` with input value at the end of the list.
* @param value - The value attached to the element.
* @returns The added `ListNode`.
*/
push(value: T): ListNode<T>;
/**
* Removes the last element of the list.
* @returns The removed `ListNode` or `undefined` if nothing was removed.
*/
pop(): ListNode<T> | undefined;
/**
* Adds an element with input value at the front of the list.
* @param value - The value attached to the element.
* @returns The added element.
*/
unshift(value: T): ListNode<T>;
/**
* Removes the first element of the list.
* @returns The removed element or `undefined` if nothing was removed.
*/
shift(): ListNode<T> | undefined;
/**
* Inserts a value before a `ListNode`. It fails if it does not belong
* to the list.
* @param value - The value to be inserted.
* @param before - The target `ListNode`.
* @returns The inserted `ListNode`, or `undefined` if the insertion failed.
*/
insertBefore(value: T, before: ListNode<T>): ListNode<T> | undefined;
/**
* Inserts a value after a `ListNode`. It fails if it does not belong
* to the list.
* @param value - The value to be inserted.
* @param after - The target `ListNode`.
* @returns The inserted `ListNode`, or `undefined` if the insertion failed.
*/
insertAfter(value: T, after: ListNode<T>): ListNode<T> | undefined;
/**
* Checks whether a value is present in the list.
* @param value - The tested value.
* @returns `true` if the value is found, `false` otherwise
*/
has(value: T): boolean;
/**
* Returns the first encountered element with matching value.
* @param value - The tested value.
* @returns The first matching `ListNode`, `undefined` if no match.
*/
get(value: T): ListNode<T> | undefined;
/**
* Returns an array of all encountered elements with matching value.
* @param value - The tested value.
* @returns An array of matching elements.
*/
getAll(value: T): ListNode<T>[];
/**
* Applies a transformation on each element and returns a new `List`.
* The original `List` remains unaltered.
* @param callback - The map function.
* @returns The new `List`
*/
map<U>(callback: ListMapper<T, U>): List<U>;
/**
* Filters out elements and returns a new `List`
* The original `Lise` remains unaltered.
* @param callback - The filter function.
* @returns The new `List`
*/
filter(callback: ListFilterer<T>): List<T>;
/**
* Accumulates the result of specific operation on each value and
* returns the accumulation as a single result.
* The original `List` remains unaltered.
* @param callback - The filter function.
* @returns The new `List`.
*/
reduce<U>(callback: ListReducer<T, U>, initialValue: U): U;
/**
* Creates an array from the `List` values.
* @returns The array of `List` values.
*/
toArray(): T[];

@@ -25,0 +102,0 @@ }

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

import DoublyLinkedList from './doubly-linked-list';
export { DoublyLinkedList, };
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DoublyLinkedList = void 0;
const doubly_linked_list_1 = require("./doubly-linked-list");
Object.defineProperty(exports, "DoublyLinkedList", { enumerable: true, get: function () { return doubly_linked_list_1.DoublyLinkedList; } });
{
"name": "ts-structures",
"version": "0.5.2",
"version": "0.5.3",
"description": "TypeScript implementation of common data structures",

@@ -5,0 +5,0 @@ "main": "index.js",

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

import Queue from './queue';
import PriorityQueue from './priority-queue';
import { Queue } from './queue';
import { PriorityQueue } from './priority-queue';
export { Queue, PriorityQueue, };

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

import Queue from './queue';
import PriorityQueue from './priority-queue';
export { Queue, PriorityQueue, };
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PriorityQueue = exports.Queue = void 0;
const queue_1 = require("./queue");
Object.defineProperty(exports, "Queue", { enumerable: true, get: function () { return queue_1.Queue; } });
const priority_queue_1 = require("./priority-queue");
Object.defineProperty(exports, "PriorityQueue", { enumerable: true, get: function () { return priority_queue_1.PriorityQueue; } });
import { CappedStructure } from '../_shared';
import { BinaryHeap } from '../heap';
/**
* Represents an element of a `PriorityQueue`. It associates a value with a priority.
*/
declare class PriorityQueueNode<T> {

@@ -8,10 +11,36 @@ value: T;

}
/**
* Priority Queue implementation based on a binary heap. It has two methods
* `enqueue` and `dequeue` to manage its elements. It implements
* the CappedStructure interface to handle overflow of a `capacity` is set.
*/
declare class PriorityQueue<T> implements CappedStructure {
values: BinaryHeap<PriorityQueueNode<T>>;
capacity: number;
/**
* Constructor takes an optional `capacity` parameter. If set,
* the PriorityQueue won't accept new elements when the lengths reaches
* the capacity, until it is dequeued.
*
* @param capacity - The maximum queue length before overflow.
*/
constructor(capacity?: number);
get length(): number;
/**
* Adds a value to the queue. Its position depends on the given priority.
* If the length already reached the (optional) capacity, enqueue
* won't perform and return `undefined`.
*
* @param value - The value associed to the element.
* @returns The length of the current Queue after insertion,
* or `-1` if it failed.
*/
enqueue(value: T, priority: number): PriorityQueueNode<T> | undefined;
/**
* Removes the element with highest priority
*
* @returns The value of the element removed.
*/
dequeue(): PriorityQueueNode<T> | undefined;
}
export default PriorityQueue;
export { PriorityQueue };

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

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {

@@ -10,4 +11,9 @@ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;

};
import { guardOverflow, } from '../_shared';
import { BinaryHeap } from '../heap';
Object.defineProperty(exports, "__esModule", { value: true });
exports.PriorityQueue = void 0;
const _shared_1 = require("../_shared");
const heap_1 = require("../heap");
/**
* Represents an element of a `PriorityQueue`. It associates a value with a priority.
*/
class PriorityQueueNode {

@@ -19,9 +25,23 @@ constructor(value, priority) {

}
/**
* Priority Queue implementation based on a binary heap. It has two methods
* `enqueue` and `dequeue` to manage its elements. It implements
* the CappedStructure interface to handle overflow of a `capacity` is set.
*/
class PriorityQueue {
/**
* Constructor takes an optional `capacity` parameter. If set,
* the PriorityQueue won't accept new elements when the lengths reaches
* the capacity, until it is dequeued.
*
* @param capacity - The maximum queue length before overflow.
*/
constructor(capacity) {
this.capacity = -1;
// higher priority -\> lower priority number, so we set a custom compareFunction
// to use the BinaryHeap as a min binary heap
const compareFunction = (a, b) => {
return a.priority < b.priority ? 1 : a.priority > b.priority ? -1 : 0;
};
this.values = new BinaryHeap().setCompareFunction(compareFunction);
this.values = new heap_1.BinaryHeap().setCompareFunction(compareFunction);
if (capacity && capacity > 0)

@@ -33,2 +53,11 @@ this.capacity = capacity;

}
/**
* Adds a value to the queue. Its position depends on the given priority.
* If the length already reached the (optional) capacity, enqueue
* won't perform and return `undefined`.
*
* @param value - The value associed to the element.
* @returns The length of the current Queue after insertion,
* or `-1` if it failed.
*/
enqueue(value, priority) {

@@ -38,2 +67,7 @@ const node = new PriorityQueueNode(value, priority);

}
/**
* Removes the element with highest priority
*
* @returns The value of the element removed.
*/
dequeue() {

@@ -44,3 +78,3 @@ return this.values.shift();

__decorate([
guardOverflow(false, undefined),
_shared_1.guardOverflow(false, undefined),
__metadata("design:type", Function),

@@ -50,3 +84,2 @@ __metadata("design:paramtypes", [Object, Number]),

], PriorityQueue.prototype, "enqueue", null);
export default PriorityQueue;
//# sourceMappingURL=priority-queue.js.map
exports.PriorityQueue = PriorityQueue;
import { CappedStructure } from '../_shared';
/**
* Represents an element of a `Queue`, wrapping a given value.
*/
declare class QueueNode<T> {

@@ -7,2 +10,7 @@ value: T;

}
/**
* Queue implementation based on a linked list. It has two methods
* `enqueue` and `dequeue` to manage its elements. It implements
* the CappedStructure interface to handle overflow of a `capacity` is set.
*/
declare class Queue<T> implements CappedStructure {

@@ -13,8 +21,35 @@ length: number;

private _last?;
/**
* Constructor takes an optional `capacity` parameter. If set,
* the Queue won't accept new elements when the lengths reaches the
* capacity, until it is dequeued.
* @param capacity - The maximum queue length before overflow.
*/
constructor(capacity?: number);
/**
* Returns the first element.
*/
first(): QueueNode<T> | undefined;
/**
* Returns the last element.
*/
last(): QueueNode<T> | undefined;
/**
* Adds an element to the end of the list and returns its length.
* If the length already reached the (optional) capacity, enqueue
* won't perform and return -1.
*
* @param value - The value associed to the element.
* @returns The length of the current Queue after insertion,
* or `-1` if it failed.
*/
enqueue(value: T): number;
/**
* Removes the first element of the list.
*
* @returns The value of the element removed.
*/
dequeue(): T | undefined;
}
export default Queue;
export { Queue };

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

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {

@@ -10,3 +11,8 @@ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;

};
import { guardOverflow, } from '../_shared';
Object.defineProperty(exports, "__esModule", { value: true });
exports.Queue = void 0;
const _shared_1 = require("../_shared");
/**
* Represents an element of a `Queue`, wrapping a given value.
*/
class QueueNode {

@@ -17,3 +23,15 @@ constructor(value) {

}
/**
* Queue implementation based on a linked list. It has two methods
* `enqueue` and `dequeue` to manage its elements. It implements
* the CappedStructure interface to handle overflow of a `capacity` is set.
*/
class Queue {
/**
* Constructor takes an optional `capacity` parameter. If set,
* the Queue won't accept new elements when the lengths reaches the
* capacity, until it is dequeued.
* @param capacity - The maximum queue length before overflow.
*/
constructor(capacity) {

@@ -25,8 +43,23 @@ this.length = 0;

}
/**
* Returns the first element.
*/
first() {
return this._first;
}
/**
* Returns the last element.
*/
last() {
return this._last;
}
/**
* Adds an element to the end of the list and returns its length.
* If the length already reached the (optional) capacity, enqueue
* won't perform and return -1.
*
* @param value - The value associed to the element.
* @returns The length of the current Queue after insertion,
* or `-1` if it failed.
*/
enqueue(value) {

@@ -41,2 +74,7 @@ const node = new QueueNode(value);

}
/**
* Removes the first element of the list.
*
* @returns The value of the element removed.
*/
dequeue() {

@@ -54,3 +92,3 @@ if (!this._first)

__decorate([
guardOverflow(false, -1),
_shared_1.guardOverflow(false, -1),
__metadata("design:type", Function),

@@ -60,3 +98,2 @@ __metadata("design:paramtypes", [Object]),

], Queue.prototype, "enqueue", null);
export default Queue;
//# sourceMappingURL=queue.js.map
exports.Queue = Queue;

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

import Stack from './stack';
import { Stack } from './stack';
export { Stack, };

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

import Stack from './stack';
export { Stack, };
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Stack = void 0;
const stack_1 = require("./stack");
Object.defineProperty(exports, "Stack", { enumerable: true, get: function () { return stack_1.Stack; } });

@@ -7,2 +7,7 @@ import { CappedStructure } from '../_shared';

}
/**
* Stack implementation based on a linked list. Its elements are managed
* by two methods `push` and `pop`. It implements the CappedStructure
* interface to handle overflow of a `capacity` is set.
*/
declare class Stack<T> implements CappedStructure {

@@ -12,6 +17,27 @@ length: number;

front?: StackNode<T>;
/**
* Constructor takes an optional `capacity` parameter. If set,
* the Stack won't accept new elements after the lengths reache
* the capacity, until an element is removed.
* @param capacity - The maximum queue length before overflow.
*/
constructor(capacity?: number);
/**
* Adds an element to the front of the stack and returns its length.
* If the length already reached the (optional) capacity, push is not
* performed and returns -1.
*
* @param value - The value associed to the pushed element.
* @returns The length of the current Queue after insertion,
* or `-1` if it failed.
*/
push(value: T): number;
/**
* Removes the first element and returns its value or `undefined` if it
* failed (empty stack).
*
* @returns The value of the removed element or `undefined` if it failed.
*/
pop(): T | undefined;
}
export default Stack;
export { Stack };

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

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {

@@ -10,3 +11,5 @@ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;

};
import { guardOverflow, } from '../_shared';
Object.defineProperty(exports, "__esModule", { value: true });
exports.Stack = void 0;
const _shared_1 = require("../_shared");
class StackNode {

@@ -18,3 +21,14 @@ constructor(value, next) {

}
/**
* Stack implementation based on a linked list. Its elements are managed
* by two methods `push` and `pop`. It implements the CappedStructure
* interface to handle overflow of a `capacity` is set.
*/
class Stack {
/**
* Constructor takes an optional `capacity` parameter. If set,
* the Stack won't accept new elements after the lengths reache
* the capacity, until an element is removed.
* @param capacity - The maximum queue length before overflow.
*/
constructor(capacity) {

@@ -26,2 +40,11 @@ this.length = 0;

}
/**
* Adds an element to the front of the stack and returns its length.
* If the length already reached the (optional) capacity, push is not
* performed and returns -1.
*
* @param value - The value associed to the pushed element.
* @returns The length of the current Queue after insertion,
* or `-1` if it failed.
*/
push(value) {

@@ -32,2 +55,8 @@ const node = new StackNode(value, this.front);

}
/**
* Removes the first element and returns its value or `undefined` if it
* failed (empty stack).
*
* @returns The value of the removed element or `undefined` if it failed.
*/
pop() {

@@ -43,3 +72,3 @@ if (!this.front)

__decorate([
guardOverflow(false, -1),
_shared_1.guardOverflow(false, -1),
__metadata("design:type", Function),

@@ -49,3 +78,2 @@ __metadata("design:paramtypes", [Object]),

], Stack.prototype, "push", null);
export default Stack;
//# sourceMappingURL=stack.js.map
exports.Stack = Stack;
import type { Comparer, CompareFunction, FilterFunction, MapFunction, ReduceFunction } from '../_shared';
import { TraverseMethod } from '../_shared';
/**
* Represents a single element of a tree. Carrying a given value,
* it is linked to maximum two child nodes via `left` and `right`
* fields.
*/
declare class BinarySearchTreeNode<T> {

@@ -8,8 +13,51 @@ value: T;

constructor(value: T);
/**
* Whether the current node has a child in the given direction.
*
* Values `-1` (left) or `1` (right) for the direction input are used
* for convenience, as it is the direct result of the `CompareFunction`.
* Case `0` is not treated as it is considered already checked.
*
* @param direction - `-1` (left) / `1` (right).
* @returns `true` / `false`.
*/
hasChild(direction: -1 | 1): boolean;
/**
* Returns the current node's child in the given direction
* (can be `undefined`).
*
* Values `-1` (left) or `1` (right) for the direction input are used
* for convenience, as it is the direct result of the `CompareFunction`.
* Case `0` is not treated as it is considered already checked.
*
* @param direction - `-1` (left) / `1` (right).
* @returns a child `BinarySearchTreeNode` or `undefined`.
*/
getChild(direction: -1 | 1): BinarySearchTreeNode<T> | undefined;
/**
* Sets the current node's child in the given direction.
*
* @param direction - `-1` (left) / `1` (right).
* @param newNode - The new Child.
*/
setChild(direction: -1 | 1, newNode: BinarySearchTreeNode<T>): void;
}
/**
* A Binary Search Tree implementation that accepts any kind of data,
* including arrays or plain objects. To do so, it must be provided
* a custom `compareFunction` that will be used to determine the position
* of the elements instead of the default comparison operators.
*/
declare class BinarySearchTree<T> implements Comparer<T> {
private _root?;
/**
* The function used to compare two elements.
* It is determinant for the tree structure.
* By default, it compares numbers so it must be replaced with a custom
* function when storing another data type.
*
* @param a - Element A
* @param b - Element B
* @returns `-1` if a \< b, `1` if a \> b, `0` if a === b
*/
compare: CompareFunction<T>;

@@ -22,20 +70,144 @@ inf: <T_1>(this: any, a: T_1, b: T_1) => boolean;

private traverseMethods;
/**
* The traverse method used when unspecified in the concerned methods.
* It can be changed via `setDefaultTraverseMethod` method.
* Possible values:
* - `TraverseMethod.BFS` / `0` (Breadth First Search)
* - `TraverseMethod.DFSPreOrder` / `1` (Depth First Search Pre Order)
* - `TraverseMethod.DFSInOrder` / `2` (Depth First Search In Order)
* - `TraverseMethod.DFSPostOrder` / `3` (Depth First Search Post Order)
*
* @defaultValue {@link TraverseMethod | TraverseMethod.DFSPreOrder}
*/
defaultTraverseMethod: TraverseMethod;
/**
* Constructor takes an optional parameter `compareFunction` to replace
* the default comparison function.
*
* @param compareFunction - The function used to compare two values.
*/
constructor(compareFunction?: CompareFunction<T>);
/**
* Returns the root node.
*
* @returns The root node
*/
root(): BinarySearchTreeNode<T> | undefined;
/**
* Replaces the current compare function with the provided
* `CompareFunction`. A compare function has the signature:
* `CompareFunction<T>(a: T, b: T) => -1 | 0 | 1`.
*
* To keep its integrity, the tree is fully rebuilt.
*
* @param compareFunction - The function to use to compare two values.
* @returns The tree instance.
*/
setCompareFunction(compareFunction: CompareFunction<T>): BinarySearchTree<T>;
/**
* Sets a default traverse method that will be used when not specified
* in methods that require traversal.
* Possible values:
* - `TraverseMethod.BFS` / `0` (Breadth First Search)
* - `TraverseMethod.DFSPreOrder` / `1` (Depth First Search Pre Order)
* - `TraverseMethod.DFSInOrder` / `2` (Depth First Search In Order)
* - `TraverseMethod.DFSPostOrder` / `3` (Depth First Search Post Order)
*
* @param traverseMethod - The default traverse method to use.
*/
setDefaultTraverseMethod(traverseMethod: TraverseMethod): void;
/**
* Inserts a new value to the tree.
* Note: the structure does not accept duplicates.
*
* @param value - The value to insert
* @returns `true` if succeeded, `false`otherwise
*/
insert(value: T): boolean;
/**
* Resets the tree, removing its elements.
*/
clear(): void;
/**
* Returns an array of the stored values. The order depends on the
* `TraverseMethod` used.
*
* @param traverseMethod - The `TraverseMethod` to use.
*/
toArray(traverseMethod?: TraverseMethod): T[];
/**
* Traverses the tree, applying a transformation to every value according
* to the given `MapFunction`. A new tree is returned, the current one is
* unaltered.
*
* @param mapFunction - The function describing the transformation to apply
* on each value.
* @param traverseMethod - The `TraverseMethod` to use.
* @param newCompareFunction - The compare function of the new tree.
* Default is set to the compare function of the current tree.
* It is **necessary** if the map function changes the values data type.
* @returns The resulting tree.
*/
map<U>(mapFunction: MapFunction<T, U>, traverseMethod?: TraverseMethod, newCompareFunction?: CompareFunction<U>): BinarySearchTree<U>;
/**
* Creates a new tree with the filtered values of the current one,
* using the input `filterFunction`. Current tree is unaltered.
*
* @param filterFunction - The `FilterFunction` to use.
* @param traverseMethod - The `TraverseMethod` to use.
* @returns The resulting tree.
*/
filter(filterFunction: FilterFunction<T>, traverseMethod?: TraverseMethod): BinarySearchTree<T>;
/**
* Computes and return a single value from the values of the tree,
* using the input `ReduceFunction`.
*
* @param reduceFunction - The `ReduceFunction` to use.
* @param initialValue - The initial value of the accumulator
* @param traverseMethod - The `TraverseMethod` to use.
* @returns The accumulated value at the end of traversal.
*/
reduce<U>(reduceFunction: ReduceFunction<T, U>, initialValue: U, traverseMethod?: TraverseMethod): U;
/**
* Traverses the tree using Breadth First Search method,
* starting from the given root. The given callback is executed
* on each value.
*
* @param root - The traversal starting point
* @param callback - A callback to execute on each value.
*/
private traverseBFS;
/**
* Traverses the tree recursively using Depth First Search method,
* and executes a callback on each value.
* This method gathers all DFS order methods into one, applying the callback
* at the right moment depending on `order` parameter.
*
* @param order - The `TraverseMethod` to use, `TraverseMethod.BFS` excluded.
* @param currentNode - The element being traversed.
* @param callback - The callback to execute on each value.
*/
private traverseDFS;
/**
* Traverses the tree using DFS PreOrder method and applies a callback
* on each value.
* @param root - The starting point of the traversal.
* @param callback - The callback to execute on each value.
*/
private traversePreOrder;
/**
* Traverses the tree using DFS InOrder method and applies a callback
* on each value.
* @param root - The starting point of the traversal.
* @param callback - The callback to execute on each value.
*/
private traverseInOrder;
/**
* Traverses the tree using DFS PostOrder method and applies a callback
* on each value.
* @param root - The starting point of the traversal.
* @param callback - The callback to execute on each value.
*/
private traversePostOrder;
}
export default BinarySearchTree;
export { TraverseMethod };
export { BinarySearchTree, TraverseMethod, };

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

import { compareMethods, TraverseMethod, } from '../_shared';
import { Queue } from '../queue';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraverseMethod = exports.BinarySearchTree = void 0;
const _shared_1 = require("../_shared");
Object.defineProperty(exports, "TraverseMethod", { enumerable: true, get: function () { return _shared_1.TraverseMethod; } });
const queue_1 = require("../queue");
/**
* Represents a single element of a tree. Carrying a given value,
* it is linked to maximum two child nodes via `left` and `right`
* fields.
*/
class BinarySearchTreeNode {

@@ -7,8 +16,35 @@ constructor(value) {

}
/**
* Whether the current node has a child in the given direction.
*
* Values `-1` (left) or `1` (right) for the direction input are used
* for convenience, as it is the direct result of the `CompareFunction`.
* Case `0` is not treated as it is considered already checked.
*
* @param direction - `-1` (left) / `1` (right).
* @returns `true` / `false`.
*/
hasChild(direction) {
return !!this.getChild(direction);
}
/**
* Returns the current node's child in the given direction
* (can be `undefined`).
*
* Values `-1` (left) or `1` (right) for the direction input are used
* for convenience, as it is the direct result of the `CompareFunction`.
* Case `0` is not treated as it is considered already checked.
*
* @param direction - `-1` (left) / `1` (right).
* @returns a child `BinarySearchTreeNode` or `undefined`.
*/
getChild(direction) {
return direction === -1 ? this.left : this.right;
}
/**
* Sets the current node's child in the given direction.
*
* @param direction - `-1` (left) / `1` (right).
* @param newNode - The new Child.
*/
setChild(direction, newNode) {

@@ -18,10 +54,32 @@ direction === -1 ? this.left = newNode : this.right = newNode;

}
/**
* A Binary Search Tree implementation that accepts any kind of data,
* including arrays or plain objects. To do so, it must be provided
* a custom `compareFunction` that will be used to determine the position
* of the elements instead of the default comparison operators.
*/
class BinarySearchTree {
/**
* Constructor takes an optional parameter `compareFunction` to replace
* the default comparison function.
*
* @param compareFunction - The function used to compare two values.
*/
constructor(compareFunction) {
this.compare = compareMethods.compare.bind(this);
this.inf = compareMethods.inf.bind(this);
this.sup = compareMethods.sup.bind(this);
this.equal = compareMethods.equal.bind(this);
this.infOrEqual = compareMethods.infOrEqual.bind(this);
this.supOrEqual = compareMethods.supOrEqual.bind(this);
/**
* The function used to compare two elements.
* It is determinant for the tree structure.
* By default, it compares numbers so it must be replaced with a custom
* function when storing another data type.
*
* @param a - Element A
* @param b - Element B
* @returns `-1` if a \< b, `1` if a \> b, `0` if a === b
*/
this.compare = _shared_1.compareMethods.compare.bind(this);
this.inf = _shared_1.compareMethods.inf.bind(this);
this.sup = _shared_1.compareMethods.sup.bind(this);
this.equal = _shared_1.compareMethods.equal.bind(this);
this.infOrEqual = _shared_1.compareMethods.infOrEqual.bind(this);
this.supOrEqual = _shared_1.compareMethods.supOrEqual.bind(this);
this.traverseMethods = [

@@ -33,12 +91,39 @@ this.traverseBFS.bind(this),

];
this.defaultTraverseMethod = TraverseMethod.DFSPreOrder;
/**
* The traverse method used when unspecified in the concerned methods.
* It can be changed via `setDefaultTraverseMethod` method.
* Possible values:
* - `TraverseMethod.BFS` / `0` (Breadth First Search)
* - `TraverseMethod.DFSPreOrder` / `1` (Depth First Search Pre Order)
* - `TraverseMethod.DFSInOrder` / `2` (Depth First Search In Order)
* - `TraverseMethod.DFSPostOrder` / `3` (Depth First Search Post Order)
*
* @defaultValue {@link TraverseMethod | TraverseMethod.DFSPreOrder}
*/
this.defaultTraverseMethod = _shared_1.TraverseMethod.DFSPreOrder;
if (compareFunction)
this.compare = compareFunction;
}
/**
* Returns the root node.
*
* @returns The root node
*/
root() {
return this._root;
}
/**
* Replaces the current compare function with the provided
* `CompareFunction`. A compare function has the signature:
* `CompareFunction<T>(a: T, b: T) => -1 | 0 | 1`.
*
* To keep its integrity, the tree is fully rebuilt.
*
* @param compareFunction - The function to use to compare two values.
* @returns The tree instance.
*/
setCompareFunction(compareFunction) {
this.compare = compareFunction;
const values = this.toArray(TraverseMethod.DFSPreOrder);
// rebuild tree according to the new compare function
const values = this.toArray(_shared_1.TraverseMethod.DFSPreOrder);
this.clear();

@@ -48,5 +133,23 @@ values.forEach(this.insert.bind(this));

}
/**
* Sets a default traverse method that will be used when not specified
* in methods that require traversal.
* Possible values:
* - `TraverseMethod.BFS` / `0` (Breadth First Search)
* - `TraverseMethod.DFSPreOrder` / `1` (Depth First Search Pre Order)
* - `TraverseMethod.DFSInOrder` / `2` (Depth First Search In Order)
* - `TraverseMethod.DFSPostOrder` / `3` (Depth First Search Post Order)
*
* @param traverseMethod - The default traverse method to use.
*/
setDefaultTraverseMethod(traverseMethod) {
this.defaultTraverseMethod = traverseMethod;
}
/**
* Inserts a new value to the tree.
* Note: the structure does not accept duplicates.
*
* @param value - The value to insert
* @returns `true` if succeeded, `false`otherwise
*/
insert(value) {

@@ -70,5 +173,14 @@ const newNode = new BinarySearchTreeNode(value);

}
/**
* Resets the tree, removing its elements.
*/
clear() {
this._root = undefined;
}
/**
* Returns an array of the stored values. The order depends on the
* `TraverseMethod` used.
*
* @param traverseMethod - The `TraverseMethod` to use.
*/
toArray(traverseMethod = this.defaultTraverseMethod) {

@@ -82,2 +194,15 @@ const reduceFunction = (values, value) => {

}
/**
* Traverses the tree, applying a transformation to every value according
* to the given `MapFunction`. A new tree is returned, the current one is
* unaltered.
*
* @param mapFunction - The function describing the transformation to apply
* on each value.
* @param traverseMethod - The `TraverseMethod` to use.
* @param newCompareFunction - The compare function of the new tree.
* Default is set to the compare function of the current tree.
* It is **necessary** if the map function changes the values data type.
* @returns The resulting tree.
*/
map(mapFunction, traverseMethod = this.defaultTraverseMethod, newCompareFunction) {

@@ -92,2 +217,10 @@ const newTree = new BinarySearchTree(newCompareFunction);

}
/**
* Creates a new tree with the filtered values of the current one,
* using the input `filterFunction`. Current tree is unaltered.
*
* @param filterFunction - The `FilterFunction` to use.
* @param traverseMethod - The `TraverseMethod` to use.
* @returns The resulting tree.
*/
filter(filterFunction, traverseMethod = this.defaultTraverseMethod) {

@@ -105,2 +238,11 @@ const newTree = new BinarySearchTree(this.compare);

}
/**
* Computes and return a single value from the values of the tree,
* using the input `ReduceFunction`.
*
* @param reduceFunction - The `ReduceFunction` to use.
* @param initialValue - The initial value of the accumulator
* @param traverseMethod - The `TraverseMethod` to use.
* @returns The accumulated value at the end of traversal.
*/
reduce(reduceFunction, initialValue, traverseMethod = this.defaultTraverseMethod) {

@@ -117,6 +259,14 @@ if (!this._root)

}
/**
* Traverses the tree using Breadth First Search method,
* starting from the given root. The given callback is executed
* on each value.
*
* @param root - The traversal starting point
* @param callback - A callback to execute on each value.
*/
traverseBFS(root, callback) {
if (!root)
return;
const queue = new Queue();
const queue = new queue_1.Queue();
queue.enqueue(root);

@@ -132,26 +282,52 @@ while (queue.first()) {

}
/**
* Traverses the tree recursively using Depth First Search method,
* and executes a callback on each value.
* This method gathers all DFS order methods into one, applying the callback
* at the right moment depending on `order` parameter.
*
* @param order - The `TraverseMethod` to use, `TraverseMethod.BFS` excluded.
* @param currentNode - The element being traversed.
* @param callback - The callback to execute on each value.
*/
traverseDFS(order, currentNode, callback) {
if (order === TraverseMethod.DFSPreOrder)
if (order === _shared_1.TraverseMethod.DFSPreOrder)
callback(currentNode.value);
if (currentNode.left)
this.traverseDFS(order, currentNode.left, callback);
if (order === TraverseMethod.DFSInOrder)
if (order === _shared_1.TraverseMethod.DFSInOrder)
callback(currentNode.value);
if (currentNode.right)
this.traverseDFS(order, currentNode.right, callback);
if (order === TraverseMethod.DFSPostOrder)
if (order === _shared_1.TraverseMethod.DFSPostOrder)
callback(currentNode.value);
}
/**
* Traverses the tree using DFS PreOrder method and applies a callback
* on each value.
* @param root - The starting point of the traversal.
* @param callback - The callback to execute on each value.
*/
traversePreOrder(root, callback) {
this.traverseDFS(TraverseMethod.DFSPreOrder, root, callback);
this.traverseDFS(_shared_1.TraverseMethod.DFSPreOrder, root, callback);
}
/**
* Traverses the tree using DFS InOrder method and applies a callback
* on each value.
* @param root - The starting point of the traversal.
* @param callback - The callback to execute on each value.
*/
traverseInOrder(root, callback) {
this.traverseDFS(TraverseMethod.DFSInOrder, root, callback);
this.traverseDFS(_shared_1.TraverseMethod.DFSInOrder, root, callback);
}
/**
* Traverses the tree using DFS PostOrder method and applies a callback
* on each value.
* @param root - The starting point of the traversal.
* @param callback - The callback to execute on each value.
*/
traversePostOrder(root, callback) {
this.traverseDFS(TraverseMethod.DFSPostOrder, root, callback);
this.traverseDFS(_shared_1.TraverseMethod.DFSPostOrder, root, callback);
}
}
export default BinarySearchTree;
export { TraverseMethod };
//# sourceMappingURL=binary-search-tree.js.map
exports.BinarySearchTree = BinarySearchTree;

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

import BinarySearchTree from './binary-search-tree';
import { BinarySearchTree } from './binary-search-tree';
export { BinarySearchTree, };

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

import BinarySearchTree from './binary-search-tree';
export { BinarySearchTree, };
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinarySearchTree = void 0;
const binary_search_tree_1 = require("./binary-search-tree");
Object.defineProperty(exports, "BinarySearchTree", { enumerable: true, get: function () { return binary_search_tree_1.BinarySearchTree; } });
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