From bac0964ac2ac7e1bfc6af24f56f1db2324d6db29 Mon Sep 17 00:00:00 2001 From: Revone Date: Wed, 15 Nov 2023 23:17:55 +0800 Subject: [PATCH] fix: Implemented a high-performance HashMap comparable to the native Map. All test cases are standardized using 'it' instead of 'test'. Enabled tsconfig's sourceMap configuration for correct line numbers in IDE testing. --- CHANGELOG.md | 2 +- README.md | 30 +- package.json | 2 +- src/data-structures/hash/hash-map.ts | 609 +++++++++++++----- src/types/data-structures/hash/hash-map.ts | 18 +- src/types/data-structures/hash/index.ts | 7 + src/utils/utils.ts | 13 + .../binary-tree/rb-tree.test.ts | 24 +- .../data-structures/hash/hash-map.test.ts | 215 ++++++- test/unit/data-structures/heap/heap.test.ts | 12 +- .../data-structures/heap/max-heap.test.ts | 8 +- .../data-structures/heap/min-heap.test.ts | 8 +- .../linked-list/skip-list.test.ts | 8 +- test/unit/data-structures/queue/deque.test.ts | 50 +- test/unit/data-structures/trie/trie.test.ts | 18 +- test/utils/array.ts | 2 +- test/utils/number.ts | 2 +- tsconfig.json | 2 +- 18 files changed, 778 insertions(+), 252 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cdca002..9ea69d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ All notable changes to this project will be documented in this file. - [Semantic Versioning](https://semver.org/spec/v2.0.0.html) - [`auto-changelog`](https://github.com/CookPete/auto-changelog) -## [v1.44.0](https://github.com/zrwusa/data-structure-typed/compare/v1.35.0...main) (upcoming) +## [v1.44.1](https://github.com/zrwusa/data-structure-typed/compare/v1.35.0...main) (upcoming) ### Changes diff --git a/README.md b/README.md index dc4a89f..4800d99 100644 --- a/README.md +++ b/README.md @@ -735,49 +735,49 @@ optimal approach to data structure design. [//]: # (No deletion!!! Start of Replace Section)
avl-tree
-
test nametime taken (ms)executions per secsample deviation
10,000 add randomly33.2330.090.00
10,000 add & delete randomly71.0714.070.00
10,000 addMany40.8924.454.42e-4
10,000 get28.0035.723.66e-4
+
test nametime taken (ms)executions per secsample deviation
10,000 add randomly36.5927.330.02
10,000 add & delete randomly71.1814.050.00
10,000 addMany45.4522.000.01
10,000 get28.0835.629.19e-4
binary-tree
-
test nametime taken (ms)executions per secsample deviation
1,000 add randomly12.4080.641.37e-4
1,000 add & delete randomly16.1361.988.55e-4
1,000 addMany10.3496.681.34e-4
1,000 get18.6553.638.17e-4
1,000 dfs155.936.416.00e-4
1,000 bfs56.0817.832.98e-4
1,000 morris257.053.890.00
+
test nametime taken (ms)executions per secsample deviation
1,000 add randomly12.4880.103.98e-4
1,000 add & delete randomly16.9159.150.00
1,000 addMany10.6693.854.57e-4
1,000 get18.3254.605.16e-4
1,000 dfs155.406.440.00
1,000 bfs57.6417.350.01
1,000 morris296.453.370.11
bst
-
test nametime taken (ms)executions per secsample deviation
10,000 add randomly28.5335.059.51e-4
10,000 add & delete randomly66.8914.959.60e-4
10,000 addMany30.9432.320.01
10,000 get28.1835.484.43e-4
+
test nametime taken (ms)executions per secsample deviation
10,000 add randomly28.7934.735.70e-4
10,000 add & delete randomly71.2014.040.00
10,000 addMany32.4530.810.01
10,000 get30.8132.460.00
rb-tree
-
test nametime taken (ms)executions per secsample deviation
100,000 add87.9311.370.00
100,000 add & delete randomly218.684.570.01
100,000 getNode99.7410.037.04e-4
+
test nametime taken (ms)executions per secsample deviation
100,000 add100.909.910.01
100,000 competitor add46.9421.310.00
100,000 add & delete randomly226.334.420.02
100,000 getNode39.1325.550.01
directed-graph
-
test nametime taken (ms)executions per secsample deviation
1,000 addVertex0.119305.581.07e-5
1,000 addEdge7.66130.500.00
1,000 getVertex0.052.03e+44.70e-6
1,000 getEdge27.2236.740.01
tarjan186.495.360.01
tarjan all190.285.260.00
topologicalSort157.126.360.00
+
test nametime taken (ms)executions per secsample deviation
1,000 addVertex0.109661.787.45e-7
1,000 addEdge6.19161.533.24e-4
1,000 getVertex0.052.03e+48.46e-6
1,000 getEdge24.5240.780.00
tarjan218.054.590.01
tarjan all219.894.550.00
topologicalSort179.795.560.01
hash-map
-
test nametime taken (ms)executions per secsample deviation
10,000 set16.0762.243.45e-4
10,000 set & get34.8328.715.83e-4
+
test nametime taken (ms)executions per secsample deviation
10,000 set0.781275.918.70e-5
10,000 competitor set0.591694.571.30e-5
10,000 set & get1.04960.332.28e-5
10,000 competitor set & get0.681474.341.08e-5
heap
-
test nametime taken (ms)executions per secsample deviation
10,000 add & pop4.63215.974.24e-5
10,000 fib add & pop380.192.630.07
+
test nametime taken (ms)executions per secsample deviation
10,000 add & pop4.63215.976.56e-5
10,000 fib add & pop358.142.790.00
doubly-linked-list
-
test nametime taken (ms)executions per secsample deviation
1,000,000 unshift218.864.570.07
1,000,000 unshift & shift171.505.830.02
1,000,000 insertBefore328.273.050.06
+
test nametime taken (ms)executions per secsample deviation
1,000,000 unshift212.234.710.03
1,000,000 competitor unshift78.9312.670.02
1,000,000 unshift & shift166.326.010.01
1,000,000 insertBefore332.923.000.04
singly-linked-list
-
test nametime taken (ms)executions per secsample deviation
10,000 push & pop224.784.450.01
10,000 insertBefore253.693.940.02
+
test nametime taken (ms)executions per secsample deviation
10,000 push & pop222.694.490.01
10,000 insertBefore250.473.990.01
max-priority-queue
-
test nametime taken (ms)executions per secsample deviation
10,000 refill & poll11.9883.500.00
+
test nametime taken (ms)executions per secsample deviation
10,000 refill & poll11.6186.122.65e-4
priority-queue
-
test nametime taken (ms)executions per secsample deviation
10,000 add & pop12.6579.048.45e-4
+
test nametime taken (ms)executions per secsample deviation
10,000 add & pop12.5879.463.35e-4
10,000 competitor add & pop2.15464.553.30e-5
deque
-
test nametime taken (ms)executions per secsample deviation
1,000,000 push231.264.320.04
1,000,000 shift28.0535.650.01
+
test nametime taken (ms)executions per secsample deviation
1,000,000 push206.224.850.04
1,000,000 competitor push22.2944.870.00
1,000,000 shift26.6537.520.00
queue
-
test nametime taken (ms)executions per secsample deviation
1,000,000 push48.0120.830.02
1,000,000 push & shift83.3412.000.00
+
test nametime taken (ms)executions per secsample deviation
1,000,000 push46.7621.390.02
1,000,000 competitor push48.7420.520.01
1,000,000 push & shift80.8712.360.00
stack
-
test nametime taken (ms)executions per secsample deviation
1,000,000 push43.2423.130.01
1,000,000 push & pop57.9617.250.02
+
test nametime taken (ms)executions per secsample deviation
1,000,000 push43.0323.240.01
1,000,000 competitor push72.2913.830.05
1,000,000 push & pop49.5520.180.01
1,000,000 competitor push & pop51.1019.570.01
trie
-
test nametime taken (ms)executions per secsample deviation
100,000 push58.1217.210.02
100,000 getWords144.396.930.13
+
test nametime taken (ms)executions per secsample deviation
100,000 push57.6717.340.03
100,000 getWords118.828.420.02
[//]: # (No deletion!!! End of Replace Section) \ No newline at end of file diff --git a/package.json b/package.json index 317f722..f55a664 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "data-structure-typed", - "version": "1.44.1", + "version": "1.45.0", "description": "Data Structures of Javascript & TypeScript. Binary Tree, BST, Graph, Heap, Priority Queue, Linked List, Queue, Deque, Stack, AVL Tree, Tree Multiset, Trie, Directed Graph, Undirected Graph, Singly Linked List, Doubly Linked List, Max Heap, Max Priority Queue, Min Heap, Min Priority Queue.", "main": "dist/cjs/index.js", "module": "dist/mjs/index.js", diff --git a/src/data-structures/hash/hash-map.ts b/src/data-structures/hash/hash-map.ts index 9595be5..247baac 100644 --- a/src/data-structures/hash/hash-map.ts +++ b/src/data-structures/hash/hash-map.ts @@ -1,5 +1,3 @@ -import {HashFunction} from '../../types'; - /** * data-structure-typed * @@ -7,179 +5,488 @@ import {HashFunction} from '../../types'; * @copyright Copyright (c) 2022 Tyler Zeng * @license MIT License */ -export class HashMap { + +import {isObjOrFunc, rangeCheck, throwRangeError} from "../../utils"; +import {HashMapLinkedNode, HashMapOptions, IterateDirection} from "../../types"; + +/** + * Because the implementation of HashMap relies on JavaScript's built-in objects and arrays, + * these underlying structures have already dealt with dynamic expansion and hash collisions. + * Therefore, there is no need for additional logic to handle these issues. + */ +class HashMapIterator { + readonly hashMap: HashMap; + + protected _node: HashMapLinkedNode; + readonly iterateDirection: IterateDirection; + protected readonly _sentinel: HashMapLinkedNode; + /** - * The constructor initializes the properties of a hash table, including the initial capacity, load factor, capacity - * multiplier, size, table array, and hash function. - * @param [initialCapacity=16] - The initial capacity is the initial size of the hash table. It determines the number of - * buckets or slots available for storing key-value pairs. The default value is 16. - * @param [loadFactor=0.75] - The load factor is a measure of how full the hash table can be before it is resized. It is - * a value between 0 and 1, where 1 means the hash table is completely full and 0 means it is completely empty. When the - * load factor is reached, the hash table will - * @param [hashFn] - The `hashFn` parameter is an optional parameter that represents the hash function used to calculate - * the index of a key in the hash table. If a custom hash function is not provided, a default hash function is used. The - * default hash function converts the key to a string, calculates the sum of the + * This is a constructor function for a linked list iterator in a HashMap data structure. + * @param node - The `node` parameter is a reference to a `HashMapLinkedNode` object. This object + * represents a node in a linked list used in a hash map data structure. It contains a key-value pair + * and references to the previous and next nodes in the linked list. + * @param sentinel - The `sentinel` parameter is a reference to a special node in a linked list. It + * is used to mark the beginning or end of the list and is typically used in data structures like + * hash maps or linked lists to simplify operations and boundary checks. + * @param hashMap - A HashMap object that stores key-value pairs. + * @param {IterateDirection} iterateDirection - The `iterateDirection` parameter is an optional + * parameter that specifies the direction in which the iterator should iterate over the elements of + * the HashMap. It can take one of the following values: + * @returns The constructor does not return anything. It is used to initialize the properties and + * methods of the object being created. */ - constructor(initialCapacity = 16, loadFactor = 0.75, hashFn?: HashFunction) { - this._initialCapacity = initialCapacity; - this._loadFactor = loadFactor; - this._capacityMultiplier = 2; - this._size = 0; - this._table = new Array(initialCapacity); - this._hashFn = - hashFn || - ((key: K) => { - const strKey = String(key); - let hash = 0; - for (let i = 0; i < strKey.length; i++) { - hash += strKey.charCodeAt(i); + constructor(node: HashMapLinkedNode, sentinel: HashMapLinkedNode, + hashMap: HashMap, iterateDirection: IterateDirection = IterateDirection.DEFAULT) { + this._node = node; + this._sentinel = sentinel; + this.iterateDirection = iterateDirection; + + + if (this.iterateDirection === IterateDirection.DEFAULT) { + this.prev = function () { + if (this._node.prev === this._sentinel) { + throwRangeError(); } - return hash % this.table.length; - }); + this._node = this._node.prev; + return this; + }; + this.next = function () { + if (this._node === this._sentinel) { + throwRangeError(); + } + this._node = this._node.next; + return this; + }; + } else { + this.prev = function () { + if (this._node.next === this._sentinel) { + throwRangeError(); + } + this._node = this._node.next; + return this; + }; + this.next = function () { + if (this._node === this._sentinel) { + throwRangeError(); + } + this._node = this._node.prev; + return this; + }; + } + this.hashMap = hashMap; } - protected _initialCapacity: number; + /** + * The above function returns a Proxy object that allows access to the key and value of a node in a + * data structure. + * @returns The code is returning a Proxy object. + */ + get current() { + if (this._node === this._sentinel) { + throwRangeError(); + } - get initialCapacity(): number { - return this._initialCapacity; + return new Proxy(<[K, V]>[], { + get: (target, prop: '0' | '1') => { + if (prop === '0') return this._node.key; + else if (prop === '1') return this._node.value; + target[0] = this._node.key; + target[1] = this._node.value; + return target[prop]; + }, + set: (_, prop: '1', newValue: V) => { + if (prop !== '1') { + throw new TypeError(`prop should be string '1'`); + } + this._node.value = newValue; + return true; + } + }); } - protected _loadFactor: number; - - get loadFactor(): number { - return this._loadFactor; + /** + * The function checks if a node is accessible. + * @returns a boolean value indicating whether the `_node` is not equal to the `_sentinel`. + */ + isAccessible() { + return this._node !== this._sentinel; } - protected _capacityMultiplier: number; - get capacityMultiplier(): number { - return this._capacityMultiplier; + prev() { + return this; } - protected _size: number; + next() { + return this; + } +} - get size(): number { +export class HashMap { + protected _nodes: HashMapLinkedNode[] = []; + protected _orgMap: Record> = {}; + protected _head: HashMapLinkedNode; + protected _tail: HashMapLinkedNode; + protected readonly _sentinel: HashMapLinkedNode; + readonly OBJ_KEY_INDEX = Symbol('OBJ_KEY_INDEX'); + + protected _size = 0; + + get size() { return this._size; } - protected _table: Array>; + /** + * The constructor initializes a HashMap object with an optional initial set of key-value pairs. + * @param hashMap - The `hashMap` parameter is an optional parameter of type `HashMapOptions<[K, + * V]>`. It is an array of key-value pairs, where each pair is represented as an array `[K, V]`. The + * `K` represents the type of the key and `V` represents the + */ + constructor(hashMap: HashMapOptions<[K, V]> = []) { + Object.setPrototypeOf(this._orgMap, null); + this._sentinel = >{}; + this._sentinel.prev = this._sentinel.next = this._head = this._tail = this._sentinel; - get table(): Array> { - return this._table; - } + hashMap.forEach(el => { + this.set(el[0], el[1]); + }); - protected _hashFn: HashFunction; - - get hashFn(): HashFunction { - return this._hashFn; - } - - set(key: K, value: V): void { - const loadFactor = this.size / this.table.length; - if (loadFactor >= this.loadFactor) { - this.resizeTable(this.table.length * this.capacityMultiplier); - } - - const index = this._hash(key); - if (!this.table[index]) { - this.table[index] = []; - } - - // Check if the key already exists in the bucket - for (let i = 0; i < this.table[index].length; i++) { - if (this.table[index][i][0] === key) { - this.table[index][i][1] = value; - return; - } - } - - this.table[index].push([key, value]); - this._size++; - } - - get(key: K): V | undefined { - const index = this._hash(key); - if (!this.table[index]) { - return undefined; - } - - for (const [k, v] of this.table[index]) { - if (k === key) { - return v; - } - } - - return undefined; - } - - delete(key: K): void { - const index = this._hash(key); - if (!this.table[index]) { - return; - } - - for (let i = 0; i < this.table[index].length; i++) { - if (this.table[index][i][0] === key) { - this.table[index].splice(i, 1); - this._size--; - - // Check if the table needs to be resized down - const loadFactor = this.size / this.table.length; - if (loadFactor < this.loadFactor / this.capacityMultiplier) { - this.resizeTable(this.table.length / this.capacityMultiplier); - } - return; - } - } - } - - *entries(): IterableIterator<[K, V]> { - for (const bucket of this.table) { - if (bucket) { - for (const [key, value] of bucket) { - yield [key, value]; - } - } - } - } - - [Symbol.iterator](): IterableIterator<[K, V]> { - return this.entries(); - } - - clear(): void { - this._size = 0; - this._table = new Array(this.initialCapacity); - } - - isEmpty(): boolean { - return this.size === 0; - } - - protected _hash(key: K): number { - return this._hashFn(key); } /** - * The `resizeTable` function resizes the table used in a hash map by creating a new table with a specified capacity and - * rehashing the key-value pairs from the old table into the new table. - * @param {number} newCapacity - The newCapacity parameter is the desired capacity for the resized table. It represents - * the number of buckets that the new table should have. + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The `set` function adds a new key-value pair to a data structure, either using an object key or a + * string key. + * @param {K} key - The `key` parameter is the key to be set in the data structure. It can be of any + * type, but typically it is a string or symbol. + * @param {V} [value] - The `value` parameter is an optional parameter of type `V`. It represents the + * value associated with the key being set in the data structure. + * @param {boolean} isObjectKey - A boolean flag indicating whether the key is an object key or not. + * @returns the size of the data structure after the key-value pair has been set. */ - protected resizeTable(newCapacity: number): void { - const newTable = new Array(newCapacity); - for (const bucket of this._table) { - // Note that this is this._table - if (bucket) { - for (const [key, value] of bucket) { - const newIndex = this._hash(key) % newCapacity; - if (!newTable[newIndex]) { - newTable[newIndex] = []; - } - newTable[newIndex].push([key, value]); - } + set(key: K, value?: V, isObjectKey: boolean = isObjOrFunc(key)) { + let newTail; + if (isObjectKey) { + const index = (>key)[this.OBJ_KEY_INDEX]; + if (index !== undefined) { + this._nodes[index].value = value; + return this._size; } + Object.defineProperty(key, this.OBJ_KEY_INDEX, { + value: this._nodes.length, + configurable: true + }); + newTail = { + key: key, + value: value, + prev: this._tail, + next: this._sentinel + }; + this._nodes.push(newTail); + } else { + const node = this._orgMap[key]; + if (node) { + node.value = value; + return this._size; + } + this._orgMap[key] = newTail = { + key: key, + value: value, + prev: this._tail, + next: this._sentinel + }; } - this._table = newTable; // Again, here is this._table + if (this._size === 0) { + this._head = newTail; + this._sentinel.next = newTail; + } else { + this._tail.next = newTail; + } + this._tail = newTail; + this._sentinel.prev = newTail; + return ++this._size; + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The function `get` retrieves the value associated with a given key from a map, either by using the + * key directly or by using an index stored in the key object. + * @param {K} key - The `key` parameter is the key used to retrieve a value from the map. It can be + * of any type, but typically it is a string or symbol. + * @param {boolean} isObjectKey - The `isObjectKey` parameter is a boolean flag that indicates + * whether the `key` parameter is an object key or not. If `isObjectKey` is `true`, it means that + * `key` is an object key. If `isObjectKey` is `false`, it means that `key` + * @returns The value associated with the given key is being returned. If the key is an object key, + * the value is retrieved from the `_nodes` array using the index stored in the `OBJ_KEY_INDEX` + * property of the key. If the key is a string key, the value is retrieved from the `_orgMap` object + * using the key itself. If the key is not found, `undefined` is + */ + get(key: K, isObjectKey: boolean = isObjOrFunc(key)) { + if (isObjectKey) { + const index = (>key)[this.OBJ_KEY_INDEX]; + return index !== undefined ? this._nodes[index].value : undefined; + } + const node = this._orgMap[key]; + return node ? node.value : undefined; + } + + /** + * Time Complexity: O(n), where n is the index. + * Space Complexity: O(1) + * + * The function `getAt` retrieves the key-value pair at a specified index in a linked list. + * @param {number} index - The index parameter is a number that represents the position of the + * element we want to retrieve from the data structure. + * @returns The method `getAt(index: number)` is returning an array containing the key-value pair at + * the specified index in the data structure. The key-value pair is represented as a tuple `[K, V]`, + * where `K` is the key and `V` is the value. + */ + getAt(index: number) { + rangeCheck(index, 0, this._size - 1); + let node = this._head; + while (index--) { + node = node.next; + } + return <[K, V]>[node.key, node.value]; + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The function `getIterator` returns a new instance of `HashMapIterator` based on the provided key + * and whether it is an object key or not. + * @param {K} key - The `key` parameter is the key used to retrieve the iterator from the HashMap. It + * can be of any type, depending on how the HashMap is implemented. + * @param {boolean} [isObjectKey] - The `isObjectKey` parameter is an optional boolean parameter that + * indicates whether the `key` parameter is an object key. If `isObjectKey` is `true`, it means that + * the `key` parameter is an object and needs to be handled differently. If `isObjectKey` is `false` + * @returns a new instance of the `HashMapIterator` class. + */ + getIterator(key: K, isObjectKey?: boolean) { + let node: HashMapLinkedNode + if (isObjectKey) { + const index = (>key)[this.OBJ_KEY_INDEX]; + if (index === undefined) { + node = this._sentinel + } else { + node = this._nodes[index]; + } + } else { + node = this._orgMap[key] || this._sentinel; + } + return new HashMapIterator(node, this._sentinel, this); + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The `delete` function removes a key-value pair from a map-like data structure. + * @param {K} key - The `key` parameter is the key that you want to delete from the data structure. + * It can be of any type, but typically it is a string or an object. + * @param {boolean} isObjectKey - The `isObjectKey` parameter is a boolean flag that indicates + * whether the `key` parameter is an object key or not. If `isObjectKey` is `true`, it means that the + * `key` parameter is an object key. If `isObjectKey` is `false`, it means that the + * @returns a boolean value. It returns `true` if the deletion was successful, and `false` if the key + * was not found. + */ + delete(key: K, isObjectKey: boolean = isObjOrFunc(key)) { + let node; + if (isObjectKey) { + const index = (>key)[this.OBJ_KEY_INDEX]; + if (index === undefined) return false; + delete (>key)[this.OBJ_KEY_INDEX]; + node = this._nodes[index]; + delete this._nodes[index]; + } else { + node = this._orgMap[key]; + if (node === undefined) return false; + delete this._orgMap[key]; + } + this._deleteNode(node); + return true; + } + + /** + * Time Complexity: O(n), where n is the index. + * Space Complexity: O(1) + * + * The `deleteAt` function deletes a node at a specified index in a linked list. + * @param {number} index - The index parameter represents the position at which the node should be + * deleted in the linked list. + * @returns The size of the list after deleting the element at the specified index. + */ + deleteAt(index: number) { + rangeCheck(index, 0, this._size - 1); + let node = this._head; + while (index--) { + node = node.next; + } + this._deleteNode(node); + return this._size; + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The function checks if a data structure is empty by comparing its size to zero. + * @returns The method is returning a boolean value indicating whether the size of the object is 0 or + * not. + */ + isEmpty() { + return this._size === 0; + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The `clear` function clears all the elements in a data structure and resets its properties. + */ + clear() { + // const OBJ_KEY_INDEX = this.OBJ_KEY_INDEX; + // this._nodes.forEach(el => { + // delete (>el.key)[OBJ_KEY_INDEX]; + // }); + this._nodes = []; + this._orgMap = {}; + Object.setPrototypeOf(this._orgMap, null); + this._size = 0; + this._head = this._tail = this._sentinel.prev = this._sentinel.next = this._sentinel; + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The function returns a new iterator object for a HashMap. + * @returns A new instance of the HashMapIterator class is being returned. + */ + get begin() { + return new HashMapIterator(this._head, this._sentinel, this); + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The function returns a new HashMapIterator object with the _sentinel value as both the start and + * end values. + * @returns A new instance of the HashMapIterator class is being returned. + */ + get end() { + return new HashMapIterator(this._sentinel, this._sentinel, this); + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The reverseBegin function returns a new HashMapIterator object that iterates over the elements of + * a HashMap in reverse order. + * @returns A new instance of the HashMapIterator class is being returned. + */ + get reverseBegin() { + return new HashMapIterator(this._tail, this._sentinel, this, IterateDirection.REVERSE); + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The reverseEnd function returns a new HashMapIterator object that iterates over the elements of a + * HashMap in reverse order. + * @returns A new instance of the HashMapIterator class is being returned. + */ + get reverseEnd() { + return new HashMapIterator(this._sentinel, this._sentinel, this, IterateDirection.REVERSE); + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The function returns the key-value pair at the front of a data structure. + * @returns The front element of the data structure, represented as a tuple with a key (K) and a + * value (V). + */ + get front() { + if (this._size === 0) return; + return <[K, V]>[this._head.key, this._head.value]; + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The function returns the key-value pair at the end of a data structure. + * @returns The method is returning an array containing the key-value pair of the tail element in the + * data structure. + */ + get back() { + if (this._size === 0) return; + return <[K, V]>[this._tail.key, this._tail.value]; + } + + /** + * Time Complexity: O(n), where n is the number of elements in the HashMap. + * Space Complexity: O(1) + * + * The `forEach` function iterates over each element in a HashMap and executes a callback function on + * each element. + * @param callback - The callback parameter is a function that will be called for each element in the + * HashMap. It takes three arguments: + */ + forEach(callback: (element: [K, V], index: number, hashMap: HashMap) => void) { + let index = 0; + let node = this._head; + while (node !== this._sentinel) { + callback(<[K, V]>[node.key, node.value], index++, this); + node = node.next; + } + } + + /** + * Time Complexity: O(n), where n is the number of elements in the HashMap. + * Space Complexity: O(1) + * + * The above function is an iterator that yields key-value pairs from a linked list. + */ + * [Symbol.iterator]() { + let node = this._head; + while (node !== this._sentinel) { + yield <[K, V]>[node.key, node.value]; + node = node.next; + } + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The `_deleteNode` function removes a node from a doubly linked list and updates the head and tail + * pointers if necessary. + * @param node - The `node` parameter is an instance of the `HashMapLinkedNode` class, which + * represents a node in a linked list. It contains a key-value pair and references to the previous + * and next nodes in the list. + */ + protected _deleteNode(node: HashMapLinkedNode) { + const {prev, next} = node; + prev.next = next; + next.prev = prev; + if (node === this._head) { + this._head = next; + } + if (node === this._tail) { + this._tail = prev; + } + this._size -= 1; } } diff --git a/src/types/data-structures/hash/hash-map.ts b/src/types/data-structures/hash/hash-map.ts index cb0ff5c..a391da1 100644 --- a/src/types/data-structures/hash/hash-map.ts +++ b/src/types/data-structures/hash/hash-map.ts @@ -1 +1,17 @@ -export {}; +export const enum IterateDirection { + DEFAULT = 0, + REVERSE = 1 +} + +export type HashMapOptions = { + sizeFunction?: number | (() => number); + fixedLength?: number; + forEach: (callback: (el: T) => void) => void; +} + +export type HashMapLinkedNode = { + key: K + value: V + next: HashMapLinkedNode + prev: HashMapLinkedNode +} \ No newline at end of file diff --git a/src/types/data-structures/hash/index.ts b/src/types/data-structures/hash/index.ts index 4e3977c..9d87f1b 100644 --- a/src/types/data-structures/hash/index.ts +++ b/src/types/data-structures/hash/index.ts @@ -1 +1,8 @@ +export * from './coordinate-map'; +export * from './coordinate-set'; +export * from './hash-map'; +export * from './hash-table'; +export * from './tree-map'; +export * from './tree-set'; + export type HashFunction = (key: K) => number; diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 37fed27..a4d0b40 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -84,3 +84,16 @@ export const getMSB = (value: number): number => { } return 1 << (31 - Math.clz32(value)); }; + +export const rangeCheck = (index: number, min: number, max: number, message = 'Index out of bounds.'): void => { + if (index < min || index > max) throw new RangeError(message); +} + +export const throwRangeError = (message = 'The value is off-limits.'): void => { + throw new RangeError(message); +} + +export const isObjOrFunc = (input: unknown): input is Record | ((...args: any[]) => any) => { + const inputType = typeof input; + return (inputType === 'object' && input !== null) || inputType === 'function'; +} \ No newline at end of file diff --git a/test/unit/data-structures/binary-tree/rb-tree.test.ts b/test/unit/data-structures/binary-tree/rb-tree.test.ts index 96c29ed..7c53e41 100644 --- a/test/unit/data-structures/binary-tree/rb-tree.test.ts +++ b/test/unit/data-structures/binary-tree/rb-tree.test.ts @@ -13,7 +13,7 @@ describe('RedBlackTree', () => { }); describe('add and getNode', () => { - test('should add and find a node in the tree', () => { + it('should add and find a node in the tree', () => { tree.add(10); tree.add(20); tree.add(5); @@ -24,7 +24,7 @@ describe('RedBlackTree', () => { expect(tree.getNode(15)).toBe(undefined); }); - test('should add and find nodes with negative keys', () => { + it('should add and find nodes with negative keys', () => { tree.add(-10); tree.add(-20); @@ -34,7 +34,7 @@ describe('RedBlackTree', () => { }); describe('deleteNode', () => { - test('should delete a node from the tree', () => { + it('should delete a node from the tree', () => { tree.add(10); tree.add(20); tree.add(5); @@ -43,7 +43,7 @@ describe('RedBlackTree', () => { expect(tree.getNode(20)).toBe(undefined); }); - test('should handle deleting a non-existent node', () => { + it('should handle deleting a non-existent node', () => { tree.add(10); tree.add(20); tree.add(5); @@ -54,7 +54,7 @@ describe('RedBlackTree', () => { }); describe('minimum', () => { - test('should find the minimum node in the tree', () => { + it('should find the minimum node in the tree', () => { tree.add(10); tree.add(20); tree.add(5); @@ -65,14 +65,14 @@ describe('RedBlackTree', () => { expect(minNode?.key).toBe(3); }); - test('should handle an empty tree', () => { + it('should handle an empty tree', () => { const minNode = tree.getLeftMost(tree.root); expect(minNode).toBe(tree.NIL); }); }); describe('getRightMost', () => { - test('should find the getRightMost node in the tree', () => { + it('should find the getRightMost node in the tree', () => { tree.add(10); tree.add(20); tree.add(5); @@ -83,14 +83,14 @@ describe('RedBlackTree', () => { expect(maxNode?.key).toBe(25); }); - test('should handle an empty tree', () => { + it('should handle an empty tree', () => { const maxNode = tree.getRightMost(tree.root); expect(maxNode).toBe(tree.NIL); }); }); describe('getSuccessor', () => { - test('should find the getSuccessor of a node', () => { + it('should find the getSuccessor of a node', () => { tree.add(10); tree.add(20); tree.add(5); @@ -103,7 +103,7 @@ describe('RedBlackTree', () => { expect(successorNode?.key).toBe(20); }); - test('should handle a node with no getSuccessor', () => { + it('should handle a node with no getSuccessor', () => { tree.add(10); tree.add(5); @@ -115,7 +115,7 @@ describe('RedBlackTree', () => { }); describe('getPredecessor', () => { - test('should find the getPredecessor of a node', () => { + it('should find the getPredecessor of a node', () => { tree.add(10); tree.add(20); tree.add(5); @@ -128,7 +128,7 @@ describe('RedBlackTree', () => { expect(predecessorNode?.key).toBe(15); }); - test('should handle a node with no getPredecessor', () => { + it('should handle a node with no getPredecessor', () => { tree.add(10); tree.add(20); diff --git a/test/unit/data-structures/hash/hash-map.test.ts b/test/unit/data-structures/hash/hash-map.test.ts index de3e2c1..e03346e 100644 --- a/test/unit/data-structures/hash/hash-map.test.ts +++ b/test/unit/data-structures/hash/hash-map.test.ts @@ -1,4 +1,7 @@ import {HashMap} from '../../../../src'; +import {getRandomInt, getRandomIntArray} from "../../../utils"; +import * as console from "console"; + describe('HashMap', () => { let hashMap: HashMap; @@ -9,10 +12,10 @@ describe('HashMap', () => { it('should initialize correctly', () => { expect(hashMap.size).toBe(0); - expect(hashMap.table.length).toBe(16); - expect(hashMap.loadFactor).toBe(0.75); - expect(hashMap.capacityMultiplier).toBe(2); - expect(hashMap.initialCapacity).toBe(16); + // expect(hashMap.table.length).toBe(16); + // expect(hashMap.loadFactor).toBe(0.75); + // expect(hashMap.capacityMultiplier).toBe(2); + // expect(hashMap.initialCapacity).toBe(16); expect(hashMap.isEmpty()).toBe(true); }); @@ -58,26 +61,23 @@ describe('HashMap', () => { hashMap.set('two', 2); hashMap.set('three', 3); - const entries = Array.from(hashMap.entries()); - expect(entries).toEqual( - expect.arrayContaining([ - ['one', 1], - ['two', 2], - ['three', 3] - ]) - ); + // const entries = Array.from(hashMap.entries()); + // expect(entries).toContainEqual(['one', 1]); + // expect(entries).toContainEqual(['two', 2]); + // expect(entries).toContainEqual(['three', 3]); }); + it('should resize the table when load factor is exceeded', () => { // Set a small initial capacity for testing resizing - hashMap = new HashMap(4, 0.5); + hashMap = new HashMap(); hashMap.set('one', 1); hashMap.set('two', 2); hashMap.set('three', 3); hashMap.set('four', 4); // This should trigger a resize - expect(hashMap.table.length).toBe(8); + // expect(hashMap.table.length).toBe(8); expect(hashMap.get('one')).toBe(1); expect(hashMap.get('two')).toBe(2); expect(hashMap.get('three')).toBe(3); @@ -89,7 +89,7 @@ describe('HashMap', () => { // A simple custom hash function that always returns 0 return 0; }; - hashMap = new HashMap(16, 0.75, customHashFn); + hashMap = new HashMap(); hashMap.set('one', 1); hashMap.set('two', 2); @@ -98,6 +98,189 @@ describe('HashMap', () => { expect(hashMap.get('two')).toBe(2); // Since the custom hash function always returns 0, these keys will collide. // Make sure they are stored separately. - expect(hashMap.table[0].length).toBe(2); + // expect(hashMap.table[0].length).toBe(2); + }); + + + it('performance', () => { + // const ht = new HashTable(); + // const st = performance.now(); + // for (let i = 0; i < 1000000; i++) { + // ht.set(i, i); + // } + // console.log(performance.now() - st); + const n = 1000000; + + // const hms = new SHashMap(); + // const ss = performance.now(); + // for (let i = 0; i < n; i++) { + // hms.put(i, i); + // } + // console.log(performance.now() - ss, 'HashMap.put'); + // const hashS = performance.now(); + // for (let i = 0; i < n; i++) { + // hms.hash(i); + // } + // console.log(performance.now() - hashS, 'hash'); + // const arr = []; + // const arrS = performance.now(); + // for (let i = 0; i < n; i++) { + // arr.push(i) + // } + // console.log(performance.now() - arrS, 'array.push'); + // const mp = new Map(); + // const smp = performance.now(); + // for (let i = 0; i < n; i++) { + // mp.set(i, i); + // } + // console.log(performance.now() - smp, 'Map.set'); + // const cHm = new CHashMap(); + // const sC = performance.now(); + // for (let i = 0; i < n; i++) { + // cHm.setElement(i, i); + // } + // console.log(performance.now() - sC, 'Competitor HashMap.setElement'); + const hm = new HashMap(); + const s = performance.now(); + for (let i = 0; i < n; i++) { + hm.set(i, i); + } + console.log(performance.now() - s, 'HashMap.set'); + }); }); + +describe('HashMap', () => { + let hashMap: HashMap; + + beforeEach(() => { + hashMap = new HashMap(); + }); + + it('should create an empty map', () => { + expect(hashMap.size).toBe(0); + }); + + it('should add a key-value pair', () => { + hashMap.set('key1', 'value1'); + expect(hashMap.get('key1')).toBe('value1'); + }); + + it('should handle object keys correctly', () => { + const keyObj = {id: 1}; + hashMap.set(keyObj, 'objectValue'); + expect(hashMap.get(keyObj)).toBe('objectValue'); + }); + + it('should handle number keys correctly', () => { + hashMap.set(999, {a:'999Value'}); + expect(hashMap.get(999)).toEqual({a:'999Value'}); + }); + + it('should update the value for an existing key', () => { + hashMap.set('key1', 'value1'); + hashMap.set('key1', 'newValue'); + expect(hashMap.get('key1')).toBe('newValue'); + }); + + it('should return undefined for a non-existent key', () => { + expect(hashMap.get('nonExistentKey')).toBeUndefined(); + }); + + it('should remove a key-value pair', () => { + hashMap.set('key1', 'value1'); + hashMap.delete('key1'); + expect(hashMap.get('key1')).toBeUndefined(); + }); + + it('should clear the map', () => { + hashMap.set('key1', 'value1'); + expect(hashMap.size).toBe(1); + + hashMap.clear(); + expect(hashMap.size).toBe(0); + }); + + it('should iterate over values', () => { + hashMap.set('key1', 'value1'); + hashMap.set('key2', 'value2'); + const values = []; + for (const value of hashMap) { + values.push(value); + } + expect(values).toEqual([['key1', 'value1'], ['key2', 'value2']]); + }); + + // test('should delete element at specific index', () => { + // hashMap.set('key1', 'value1'); + // hashMap.set('key2', 'value2'); + // hashMap.deleteAt(0); + // expect(hashMap.get('key1')).toBeUndefined(); + // expect(hashMap.size).toBe(1); + // }); + function compareHashMaps(hashMap: HashMap, stdMap: Map) { + expect(hashMap.size).toEqual(stdMap.size); + let index = 0; + stdMap.forEach((value, key) => { + if (index === 0) { + expect(hashMap.front).toEqual([key, value]); + expect(hashMap.begin.current[0]).toEqual(key); + } else if (index === hashMap.size - 1) { + expect(hashMap.back).toEqual([key, value]); + expect(hashMap.reverseBegin.current[0]).toEqual(key); + } else if (index <= 1000) { + expect(hashMap.getAt(index)).toEqual([key, value]); + } + expect(hashMap.get(key)).toEqual(value); + expect(hashMap.getIterator(key).current[1]).toEqual(value); + index++; + }); + } + const stdMap: Map = new Map(); + const arr: number[] = getRandomIntArray(10000, 1, 10000); + + it('delete test', () => { + for (const item of arr) { + stdMap.set(item, item); + hashMap.set(item, item); + } + for (const item of arr) { + if (Math.random() > 0.6) { + expect(hashMap.delete(item)).toEqual(stdMap.delete(item)); + } + } + compareHashMaps(hashMap, stdMap); + + for (let i = 0; i < 10000; ++i) { + const random = getRandomInt(0, 100); + expect(hashMap.delete(random)).toEqual(stdMap.delete(random)); + } + compareHashMaps(hashMap, stdMap); + }); + test('should iterate correctly with reverse iterators', () => { + hashMap.set('key1', 'value1'); + hashMap.set('key2', 'value2'); + const iterator = hashMap.reverseBegin; + expect(iterator.next().current).toEqual(['key1', 'value1']); + + }); + + test('should return the last element', () => { + hashMap.set('key1', 'value1'); + hashMap.set('key2', 'value2'); + expect(hashMap.back).toEqual(['key2', 'value2']); + }); + + test('should return undefined for empty map', () => { + expect(hashMap.back).toBeUndefined(); + }); + test('should get element at specific index', () => { + hashMap.set('key1', 'value1'); + hashMap.set('key2', 'value2'); + expect(hashMap.getAt(1)).toEqual(['key2', 'value2']); + }); + + + +}) + diff --git a/test/unit/data-structures/heap/heap.test.ts b/test/unit/data-structures/heap/heap.test.ts index 1f9d5b4..caa6698 100644 --- a/test/unit/data-structures/heap/heap.test.ts +++ b/test/unit/data-structures/heap/heap.test.ts @@ -62,13 +62,13 @@ describe('FibonacciHeap', () => { heap = new FibonacciHeap(); }); - test('push & peek', () => { + it('push & peek', () => { heap.push(10); heap.push(5); expect(heap.peek()).toBe(5); }); - test('pop', () => { + it('pop', () => { heap.push(10); heap.push(5); heap.push(15); @@ -77,11 +77,11 @@ describe('FibonacciHeap', () => { expect(heap.pop()).toBe(15); }); - test('pop on an empty heap', () => { + it('pop on an empty heap', () => { expect(heap.pop()).toBeUndefined(); }); - test('size', () => { + it('size', () => { expect(heap.size).toBe(0); heap.push(10); expect(heap.size).toBe(1); @@ -89,7 +89,7 @@ describe('FibonacciHeap', () => { expect(heap.size).toBe(0); }); - test('clear', () => { + it('clear', () => { heap.push(10); heap.push(5); heap.clear(); @@ -97,7 +97,7 @@ describe('FibonacciHeap', () => { expect(heap.peek()).toBeUndefined(); }); - test('custom comparator', () => { + it('custom comparator', () => { const maxHeap = new FibonacciHeap((a, b) => b - a); maxHeap.push(10); maxHeap.push(5); diff --git a/test/unit/data-structures/heap/max-heap.test.ts b/test/unit/data-structures/heap/max-heap.test.ts index 67ec6f8..74dd554 100644 --- a/test/unit/data-structures/heap/max-heap.test.ts +++ b/test/unit/data-structures/heap/max-heap.test.ts @@ -8,7 +8,7 @@ describe('MaxHeap', () => { maxHeap = new MaxHeap({comparator: numberComparator}); }); - test('add and poll elements in descending order', () => { + it('add and poll elements in descending order', () => { maxHeap.add(3); maxHeap.add(1); maxHeap.add(4); @@ -20,7 +20,7 @@ describe('MaxHeap', () => { expect(maxHeap.poll()).toBe(1); }); - test('peek at the top element without removing it', () => { + it('peek at the top element without removing it', () => { maxHeap.add(3); maxHeap.add(1); maxHeap.add(4); @@ -30,7 +30,7 @@ describe('MaxHeap', () => { expect(maxHeap.size).toBe(4); }); - test('sort elements in descending order', () => { + it('sort elements in descending order', () => { maxHeap.add(3); maxHeap.add(1); maxHeap.add(4); @@ -40,7 +40,7 @@ describe('MaxHeap', () => { expect(sortedArray).toEqual([4, 3, 2, 1]); }); - test('check if the heap is empty', () => { + it('check if the heap is empty', () => { expect(maxHeap.isEmpty()).toBe(true); maxHeap.add(5); diff --git a/test/unit/data-structures/heap/min-heap.test.ts b/test/unit/data-structures/heap/min-heap.test.ts index d462c9b..2f679af 100644 --- a/test/unit/data-structures/heap/min-heap.test.ts +++ b/test/unit/data-structures/heap/min-heap.test.ts @@ -8,7 +8,7 @@ describe('MinHeap', () => { minHeap = new MinHeap({comparator: numberComparator}); }); - test('add and poll elements in ascending order', () => { + it('add and poll elements in ascending order', () => { minHeap.add(3); minHeap.add(1); minHeap.add(4); @@ -20,7 +20,7 @@ describe('MinHeap', () => { expect(minHeap.poll()).toBe(4); }); - test('peek at the top element without removing it', () => { + it('peek at the top element without removing it', () => { minHeap.add(3); minHeap.add(1); minHeap.add(4); @@ -30,7 +30,7 @@ describe('MinHeap', () => { expect(minHeap.size).toBe(4); }); - test('sort elements in ascending order', () => { + it('sort elements in ascending order', () => { minHeap.add(3); minHeap.add(1); minHeap.add(4); @@ -40,7 +40,7 @@ describe('MinHeap', () => { expect(sortedArray).toEqual([1, 2, 3, 4]); }); - test('check if the heap is empty', () => { + it('check if the heap is empty', () => { expect(minHeap.isEmpty()).toBe(true); minHeap.add(5); diff --git a/test/unit/data-structures/linked-list/skip-list.test.ts b/test/unit/data-structures/linked-list/skip-list.test.ts index e6d189b..05fb65c 100644 --- a/test/unit/data-structures/linked-list/skip-list.test.ts +++ b/test/unit/data-structures/linked-list/skip-list.test.ts @@ -65,21 +65,21 @@ describe('SkipList', () => { skipList.add(4, 'Four'); }); - test('getFirst() should return the getFirst element', () => { + it('getFirst() should return the getFirst element', () => { expect(skipList.getFirst()).toBe('One'); }); - test('getLast() should return the getLast element', () => { + it('getLast() should return the getLast element', () => { expect(skipList.getLast()).toBe('Four'); }); - test('higher(key) should return the getFirst element greater than the given key', () => { + it('higher(key) should return the getFirst element greater than the given key', () => { expect(skipList.higher(2)).toBe('Three'); expect(skipList.higher(3)).toBe('Four'); expect(skipList.higher(4)).toBeUndefined(); }); - test('lower(key) should return the getLast element less than the given key', () => { + it('lower(key) should return the getLast element less than the given key', () => { expect(skipList.lower(2)).toBe('One'); expect(skipList.lower(1)).toBe(null); }); diff --git a/test/unit/data-structures/queue/deque.test.ts b/test/unit/data-structures/queue/deque.test.ts index e8cd139..d73ceed 100644 --- a/test/unit/data-structures/queue/deque.test.ts +++ b/test/unit/data-structures/queue/deque.test.ts @@ -155,12 +155,12 @@ describe('Deque', () => { deque = new Deque(); }); - test('should initialize an empty deque', () => { + it('should initialize an empty deque', () => { expect(deque.size).toBe(0); expect(deque.isEmpty()).toBe(true); }); - test('should add elements to the front and back', () => { + it('should add elements to the front and back', () => { deque.addFirst(1); deque.addLast(2); @@ -169,7 +169,7 @@ describe('Deque', () => { expect(deque.getLast()).toBe(2); }); - test('should remove elements from the front and back', () => { + it('should remove elements from the front and back', () => { deque.addFirst(1); deque.addLast(2); @@ -181,7 +181,7 @@ describe('Deque', () => { expect(lastElement).toBe(2); }); - test('should get elements by index', () => { + it('should get elements by index', () => { deque.addLast(1); deque.addLast(2); deque.addLast(3); @@ -191,13 +191,13 @@ describe('Deque', () => { expect(deque.getAt(2)).toBe(3); }); - test('should return null for out-of-bounds index', () => { + it('should return null for out-of-bounds index', () => { expect(deque.getAt(0)).toBe(undefined); expect(deque.getAt(1)).toBe(undefined); expect(deque.getAt(-1)).toBe(undefined); }); - test('should check if the deque is empty', () => { + it('should check if the deque is empty', () => { expect(deque.isEmpty()).toBe(true); deque.addLast(1); @@ -215,12 +215,12 @@ describe('ArrayDeque', () => { deque = new ArrayDeque(); }); - test('should initialize an empty deque', () => { + it('should initialize an empty deque', () => { expect(deque.size).toBe(0); expect(deque.isEmpty()).toBe(true); }); - test('should add elements to the front and back', () => { + it('should add elements to the front and back', () => { deque.addFirst(1); deque.addLast(2); @@ -229,7 +229,7 @@ describe('ArrayDeque', () => { expect(deque.getLast()).toBe(2); }); - test('should remove elements from the front and back', () => { + it('should remove elements from the front and back', () => { deque.addFirst(1); deque.addLast(2); @@ -241,7 +241,7 @@ describe('ArrayDeque', () => { expect(lastElement).toBe(2); }); - test('should get elements by index', () => { + it('should get elements by index', () => { deque.addLast(1); deque.addLast(2); deque.addLast(3); @@ -251,13 +251,13 @@ describe('ArrayDeque', () => { expect(deque.get(2)).toBe(3); }); - test('should return null for out-of-bounds index', () => { + it('should return null for out-of-bounds index', () => { expect(deque.get(0)).toBe(null); expect(deque.get(1)).toBe(null); expect(deque.get(-1)).toBe(null); }); - test('should check if the deque is empty', () => { + it('should check if the deque is empty', () => { expect(deque.isEmpty()).toBe(true); deque.addLast(1); @@ -267,7 +267,7 @@ describe('ArrayDeque', () => { expect(deque.isEmpty()).toBe(true); }); - test('should set elements at a specific index', () => { + it('should set elements at a specific index', () => { deque.addLast(1); deque.addLast(2); deque.addLast(3); @@ -279,7 +279,7 @@ describe('ArrayDeque', () => { expect(deque.get(2)).toBe(3); }); - test('should insert elements at a specific index', () => { + it('should insert elements at a specific index', () => { deque.addLast(1); deque.addLast(2); deque.addLast(3); @@ -293,7 +293,7 @@ describe('ArrayDeque', () => { expect(deque.get(3)).toBe(3); }); - test('should delete elements at a specific index', () => { + it('should delete elements at a specific index', () => { deque.addLast(1); deque.addLast(2); deque.addLast(3); @@ -314,7 +314,7 @@ describe('ObjectDeque', () => { deque = new ObjectDeque(); }); - test('should add elements to the front of the deque', () => { + it('should add elements to the front of the deque', () => { deque.addFirst(1); deque.addFirst(2); @@ -323,7 +323,7 @@ describe('ObjectDeque', () => { expect(deque.getLast()).toBe(1); }); - test('should add elements to the end of the deque', () => { + it('should add elements to the end of the deque', () => { deque.addLast(1); deque.addLast(2); @@ -332,7 +332,7 @@ describe('ObjectDeque', () => { expect(deque.getLast()).toBe(2); }); - test('should remove elements from the front of the deque', () => { + it('should remove elements from the front of the deque', () => { deque.addLast(1); deque.addLast(2); @@ -343,7 +343,7 @@ describe('ObjectDeque', () => { expect(deque.getFirst()).toBe(2); }); - test('should remove elements from the end of the deque', () => { + it('should remove elements from the end of the deque', () => { deque.addLast(1); deque.addLast(2); @@ -354,7 +354,7 @@ describe('ObjectDeque', () => { expect(deque.getLast()).toBe(2); }); - test('should return the element at the front of the deque without removing it', () => { + it('should return the element at the front of the deque without removing it', () => { deque.addFirst(1); deque.addFirst(2); @@ -362,7 +362,7 @@ describe('ObjectDeque', () => { expect(deque.size).toBe(2); }); - test('should return the element at the end of the deque without removing it', () => { + it('should return the element at the end of the deque without removing it', () => { deque.addLast(1); deque.addLast(2); @@ -370,7 +370,7 @@ describe('ObjectDeque', () => { expect(deque.size).toBe(2); }); - test('should return the correct size of the deque', () => { + it('should return the correct size of the deque', () => { deque.addFirst(1); deque.addLast(2); deque.addLast(3); @@ -378,7 +378,7 @@ describe('ObjectDeque', () => { expect(deque.size).toBe(3); }); - test('should check if the deque is empty', () => { + it('should check if the deque is empty', () => { expect(deque.isEmpty()).toBe(true); deque.addFirst(1); @@ -386,7 +386,7 @@ describe('ObjectDeque', () => { expect(deque.isEmpty()).toBe(false); }); - test('should set elements at a specific index', () => { + it('should set elements at a specific index', () => { deque.addFirst(1); deque.addLast(2); deque.addLast(3); @@ -396,7 +396,7 @@ describe('ObjectDeque', () => { expect(deque.getLast()).toBe(3); }); - test('should insert elements at a specific index', () => { + it('should insert elements at a specific index', () => { deque.addFirst(1); deque.addLast(2); deque.addLast(3); diff --git a/test/unit/data-structures/trie/trie.test.ts b/test/unit/data-structures/trie/trie.test.ts index 4034adf..3807572 100644 --- a/test/unit/data-structures/trie/trie.test.ts +++ b/test/unit/data-structures/trie/trie.test.ts @@ -761,7 +761,7 @@ describe('Trie operations', () => { trie = new Trie(); }); - test('Add and Find Words', () => { + it('Add and Find Words', () => { trie.add('apple'); trie.add('banana'); expect(trie.has('apple')).toBe(true); @@ -769,7 +769,7 @@ describe('Trie operations', () => { expect(trie.has('cherry')).toBe(false); }); - test('Remove Words', () => { + it('Remove Words', () => { trie.add('apple'); trie.add('banana'); expect(trie.delete('apple')).toBe(true); @@ -777,39 +777,39 @@ describe('Trie operations', () => { expect(trie.delete('cherry')).toBe(false); }); - test('Case Sensitivity', () => { + it('Case Sensitivity', () => { const caseInsensitiveTrie = new Trie(['apple', 'Banana'], false); expect(caseInsensitiveTrie.has('APPLE')).toBe(true); expect(caseInsensitiveTrie.has('banana')).toBe(true); expect(caseInsensitiveTrie.has('Cherry')).toBe(false); }); - test('Pure Prefix Check', () => { + it('Pure Prefix Check', () => { trie.add('apple'); expect(trie.hasPurePrefix('appl')).toBe(true); expect(trie.hasPurePrefix('apple')).toBe(false); }); - test('Prefix Check', () => { + it('Prefix Check', () => { trie.add('apple'); expect(trie.hasPrefix('app')).toBe(true); expect(trie.hasPrefix('ban')).toBe(false); }); - test('Common Prefix Check', () => { + it('Common Prefix Check', () => { trie.add('apple'); trie.add('appetizer'); expect(trie.hasCommonPrefix('app')).toBe(true); expect(trie.hasCommonPrefix('apple')).toBe(false); }); - test('Longest Common Prefix', () => { + it('Longest Common Prefix', () => { trie.add('apple'); trie.add('appetizer'); expect(trie.getLongestCommonPrefix()).toBe('app'); }); - test('Get Words by Prefix', () => { + it('Get Words by Prefix', () => { trie.add('apple'); trie.add('appetizer'); trie.add('banana'); @@ -817,7 +817,7 @@ describe('Trie operations', () => { expect(words).toEqual(['apple', 'appetizer']); }); - test('Tree Height', () => { + it('Tree Height', () => { trie.add('apple'); trie.add('banana'); expect(trie.getHeight()).toBe(6); // Assuming 'apple' and 'banana' are the longest words. diff --git a/test/utils/array.ts b/test/utils/array.ts index 94f3fbc..c15d5fe 100644 --- a/test/utils/array.ts +++ b/test/utils/array.ts @@ -1,6 +1,6 @@ import {getRandomInt} from './number'; -export function getRandomIntArray(length: number, min: number = -1000, max: number = 1000, isDistinct = true) { +export function getRandomIntArray(length: number = 1000, min: number = -1000, max: number = 1000, isDistinct = true) { if (isDistinct) { const set = new Set(); const ans: number[] = []; diff --git a/test/utils/number.ts b/test/utils/number.ts index 04c3210..15b3686 100644 --- a/test/utils/number.ts +++ b/test/utils/number.ts @@ -1,4 +1,4 @@ -export function getRandomInt(min: number, max: number) { +export function getRandomInt(min: number = 0, max: number = 1000) { return Math.floor(Math.random() * (max - min + 1)) + min; } diff --git a/tsconfig.json b/tsconfig.json index bed0041..4ef6131 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,7 +6,7 @@ "module": "NodeNext", "target": "ESNext", "moduleResolution": "NodeNext", - "sourceMap": false + "sourceMap": true // It actually affects the error line number positioning in IDE test cases running. }, "include": [ "./src/**/*.ts",