red-black-tree-typed 2.2.1 → 2.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +92 -37
  2. package/dist/cjs/index.cjs +163 -0
  3. package/dist/cjs/index.cjs.map +1 -1
  4. package/dist/cjs-legacy/index.cjs +164 -0
  5. package/dist/cjs-legacy/index.cjs.map +1 -1
  6. package/dist/esm/index.mjs +163 -0
  7. package/dist/esm/index.mjs.map +1 -1
  8. package/dist/esm-legacy/index.mjs +164 -0
  9. package/dist/esm-legacy/index.mjs.map +1 -1
  10. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +96 -2
  11. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +103 -7
  12. package/dist/types/data-structures/binary-tree/bst.d.ts +156 -13
  13. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +84 -35
  14. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +2 -2
  15. package/dist/types/data-structures/graph/directed-graph.d.ts +126 -1
  16. package/dist/types/data-structures/graph/undirected-graph.d.ts +160 -1
  17. package/dist/types/data-structures/hash/hash-map.d.ts +110 -27
  18. package/dist/types/data-structures/heap/heap.d.ts +107 -58
  19. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +72 -404
  20. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +121 -5
  21. package/dist/types/data-structures/queue/deque.d.ts +95 -67
  22. package/dist/types/data-structures/queue/queue.d.ts +90 -34
  23. package/dist/types/data-structures/stack/stack.d.ts +58 -40
  24. package/dist/types/data-structures/trie/trie.d.ts +109 -47
  25. package/dist/types/interfaces/binary-tree.d.ts +1 -0
  26. package/dist/umd/red-black-tree-typed.js +164 -0
  27. package/dist/umd/red-black-tree-typed.js.map +1 -1
  28. package/dist/umd/red-black-tree-typed.min.js +3 -3
  29. package/dist/umd/red-black-tree-typed.min.js.map +1 -1
  30. package/package.json +2 -2
  31. package/src/data-structures/binary-tree/avl-tree.ts +96 -2
  32. package/src/data-structures/binary-tree/binary-tree.ts +117 -7
  33. package/src/data-structures/binary-tree/bst.ts +322 -13
  34. package/src/data-structures/binary-tree/red-black-tree.ts +84 -35
  35. package/src/data-structures/binary-tree/tree-multi-map.ts +2 -2
  36. package/src/data-structures/graph/directed-graph.ts +126 -1
  37. package/src/data-structures/graph/undirected-graph.ts +160 -1
  38. package/src/data-structures/hash/hash-map.ts +110 -27
  39. package/src/data-structures/heap/heap.ts +107 -58
  40. package/src/data-structures/linked-list/doubly-linked-list.ts +72 -404
  41. package/src/data-structures/linked-list/singly-linked-list.ts +121 -5
  42. package/src/data-structures/queue/deque.ts +95 -67
  43. package/src/data-structures/queue/queue.ts +90 -34
  44. package/src/data-structures/stack/stack.ts +58 -40
  45. package/src/data-structures/trie/trie.ts +109 -47
  46. package/src/interfaces/binary-tree.ts +2 -0
package/README.md CHANGED
@@ -224,49 +224,104 @@ lastBFSNodes[0].id // 12
224
224
 
225
225
  [//]: # (No deletion!!! Start of Example Replace Section)
226
226
 
227
- ### using Red-Black Tree as a price-based index for stock data
227
+ ### basic Red-Black Tree with simple number keys
228
228
  ```typescript
229
- // Define the structure of individual stock records
230
- interface StockRecord {
231
- price: number; // Stock price (key for indexing)
232
- symbol: string; // Stock ticker symbol
233
- volume: number; // Trade volume
229
+ // Create a simple Red-Black Tree with numeric keys
230
+ const tree = new RedBlackTree([5, 2, 8, 1, 9]);
231
+
232
+ tree.print();
233
+ // _2___
234
+ // / \
235
+ // 1 _8_
236
+ // / \
237
+ // 5 9
238
+
239
+ // Verify the tree maintains sorted order
240
+ console.log([...tree.keys()]); // [1, 2, 5, 8, 9];
241
+
242
+ // Check size
243
+ console.log(tree.size); // 5;
244
+ ```
245
+
246
+ ### Red-Black Tree with key-value pairs for lookups
247
+ ```typescript
248
+ interface Employee {
249
+ id: number;
250
+ name: string;
251
+ }
252
+
253
+ // Create tree with employee data
254
+ const employees = new RedBlackTree<number, Employee>([
255
+ [1, { id: 1, name: 'Alice' }],
256
+ [3, { id: 3, name: 'Charlie' }],
257
+ [2, { id: 2, name: 'Bob' }]
258
+ ]);
259
+
260
+ // Retrieve employee by ID
261
+ const alice = employees.get(1);
262
+ console.log(alice?.name); // 'Alice';
263
+
264
+ // Verify sorted order by ID
265
+ console.log([...employees.keys()]); // [1, 2, 3];
266
+ ```
267
+
268
+ ### Red-Black Tree range search for filtering
269
+ ```typescript
270
+ interface Product {
271
+ name: string;
272
+ price: number;
234
273
  }
235
274
 
236
- // Simulate stock market data as it might come from an external feed
237
- const marketStockData: StockRecord[] = [
238
- { price: 142.5, symbol: 'AAPL', volume: 1000000 },
239
- { price: 335.2, symbol: 'MSFT', volume: 800000 },
240
- { price: 3285.04, symbol: 'AMZN', volume: 500000 },
241
- { price: 267.98, symbol: 'META', volume: 750000 },
242
- { price: 234.57, symbol: 'GOOGL', volume: 900000 }
243
- ];
244
-
245
- // Extend the stock record type to include metadata for database usage
246
- type StockTableRecord = StockRecord & { lastUpdated: Date };
247
-
248
- // Create a Red-Black Tree to index stock records by price
249
- // Simulates a database index with stock price as the key for quick lookups
250
- const priceIndex = new RedBlackTree<number, StockTableRecord, StockRecord>(marketStockData, {
251
- toEntryFn: stockRecord => [
252
- stockRecord.price, // Use stock price as the key
253
- {
254
- ...stockRecord,
255
- lastUpdated: new Date() // Add a timestamp for when the record was indexed
256
- }
257
- ]
275
+ const products = new RedBlackTree<number, Product>([
276
+ [10, { name: 'Item A', price: 10 }],
277
+ [25, { name: 'Item B', price: 25 }],
278
+ [40, { name: 'Item C', price: 40 }],
279
+ [50, { name: 'Item D', price: 50 }]
280
+ ]);
281
+
282
+ // Find products in price range [20, 45]
283
+ const pricesInRange = products.rangeSearch([20, 45], node => {
284
+ return products.get(node)?.name;
258
285
  });
259
286
 
260
- // Query the stock with the highest price
261
- const highestPricedStock = priceIndex.getRightMost();
262
- console.log(priceIndex.get(highestPricedStock)?.symbol); // 'AMZN' // Amazon has the highest price
287
+ console.log(pricesInRange); // ['Item B', 'Item C'];
288
+ ```
289
+
290
+ ### Red-Black Tree as database index for stock market data
291
+ ```typescript
292
+ interface StockPrice {
293
+ symbol: string;
294
+ volume: number;
295
+ timestamp: Date;
296
+ }
297
+
298
+ // Simulate real-time stock price index
299
+ const priceIndex = new RedBlackTree<number, StockPrice>([
300
+ [142.5, { symbol: 'AAPL', volume: 1000000, timestamp: new Date() }],
301
+ [335.2, { symbol: 'MSFT', volume: 800000, timestamp: new Date() }],
302
+ [3285.04, { symbol: 'AMZN', volume: 500000, timestamp: new Date() }],
303
+ [267.98, { symbol: 'META', volume: 750000, timestamp: new Date() }],
304
+ [234.57, { symbol: 'GOOGL', volume: 900000, timestamp: new Date() }]
305
+ ]);
306
+
307
+ // Find highest-priced stock
308
+ const maxPrice = priceIndex.getRightMost();
309
+ console.log(priceIndex.get(maxPrice)?.symbol); // 'AMZN';
310
+
311
+ // Find stocks in price range [200, 400] for portfolio balancing
312
+ const stocksInRange = priceIndex.rangeSearch([200, 400], node => {
313
+ const stock = priceIndex.get(node);
314
+ return {
315
+ symbol: stock?.symbol,
316
+ price: node,
317
+ volume: stock?.volume
318
+ };
319
+ });
263
320
 
264
- // Query stocks within a specific price range (200 to 400)
265
- const stocksInRange = priceIndex.rangeSearch(
266
- [200, 400], // Price range
267
- node => priceIndex.get(node)?.symbol // Extract stock symbols for the result
268
- );
269
- console.log(stocksInRange); // ['GOOGL', 'META', 'MSFT']
321
+ console.log(stocksInRange.length); // 3;
322
+ console.log(stocksInRange.some((s: any) => s.symbol === 'GOOGL')); // true;
323
+ console.log(stocksInRange.some((s: any) => s.symbol === 'META')); // true;
324
+ console.log(stocksInRange.some((s: any) => s.symbol === 'MSFT')); // true;
270
325
  ```
271
326
 
272
327
  [//]: # (No deletion!!! End of Example Replace Section)
@@ -1463,6 +1463,17 @@ var BinaryTree = class extends IterableEntryBase {
1463
1463
  }
1464
1464
  return false;
1465
1465
  }
1466
+ /**
1467
+ * Adds or updates a new node to the tree.
1468
+ * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation adds the node at the first available position in a level-order (BFS) traversal. This is NOT a Binary Search Tree insertion. Time O(N), where N is the number of nodes. It must traverse level-by-level to find an empty slot. Space O(N) in the worst case for the BFS queue (e.g., a full last level).
1469
+ *
1470
+ * @param keyNodeOrEntry - The key, node, or entry to add or update.
1471
+ * @param [value] - The value, if providing just a key.
1472
+ * @returns True if the addition was successful, false otherwise.
1473
+ */
1474
+ set(keyNodeOrEntry, value) {
1475
+ return this.add(keyNodeOrEntry, value);
1476
+ }
1466
1477
  /**
1467
1478
  * Adds multiple items to the tree.
1468
1479
  * @remarks Time O(N * M), where N is the number of items to add and M is the size of the tree at insertion (due to O(M) `add` operation). Space O(M) (from `add`) + O(N) (for the `inserted` array).
@@ -1490,6 +1501,17 @@ var BinaryTree = class extends IterableEntryBase {
1490
1501
  }
1491
1502
  return inserted;
1492
1503
  }
1504
+ /**
1505
+ * Adds or updates multiple items to the tree.
1506
+ * @remarks Time O(N * M), where N is the number of items to add and M is the size of the tree at insertion (due to O(M) `add` operation). Space O(M) (from `add`) + O(N) (for the `inserted` array).
1507
+ *
1508
+ * @param keysNodesEntriesOrRaws - An iterable of items to add or update.
1509
+ * @param [values] - An optional parallel iterable of values.
1510
+ * @returns An array of booleans indicating the success of each individual `add` operation.
1511
+ */
1512
+ setMany(keysNodesEntriesOrRaws, values) {
1513
+ return this.addMany(keysNodesEntriesOrRaws, values);
1514
+ }
1493
1515
  /**
1494
1516
  * Merges another tree into this one by adding all its nodes.
1495
1517
  * @remarks Time O(N * M), same as `addMany`, where N is the size of `anotherTree` and M is the size of this tree. Space O(M) (from `add`).
@@ -3188,6 +3210,32 @@ var BST = class extends BinaryTree {
3188
3210
  else _iterate();
3189
3211
  return inserted;
3190
3212
  }
3213
+ /**
3214
+ * Returns the first node with a key greater than or equal to the given key.
3215
+ * This is equivalent to C++ std::lower_bound on a BST.
3216
+ * Supports RECURSIVE and ITERATIVE implementations.
3217
+ * Time Complexity: O(log n) on average, O(h) where h is tree height.
3218
+ * Space Complexity: O(h) for recursion, O(1) for iteration.
3219
+ * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.
3220
+ * @param iterationType The iteration type (RECURSIVE or ITERATIVE). Defaults to this.iterationType.
3221
+ * @returns The first node with key >= given key, or undefined if no such node exists.
3222
+ */
3223
+ lowerBound(keyNodeEntryOrPredicate, iterationType = this.iterationType) {
3224
+ return this._bound(keyNodeEntryOrPredicate, true, iterationType);
3225
+ }
3226
+ /**
3227
+ * Returns the first node with a key strictly greater than the given key.
3228
+ * This is equivalent to C++ std::upper_bound on a BST.
3229
+ * Supports RECURSIVE and ITERATIVE implementations.
3230
+ * Time Complexity: O(log n) on average, O(h) where h is tree height.
3231
+ * Space Complexity: O(h) for recursion, O(1) for iteration.
3232
+ * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.
3233
+ * @param iterationType The iteration type (RECURSIVE or ITERATIVE). Defaults to this.iterationType.
3234
+ * @returns The first node with key > given key, or undefined if no such node exists.
3235
+ */
3236
+ upperBound(keyNodeEntryOrPredicate, iterationType = this.iterationType) {
3237
+ return this._bound(keyNodeEntryOrPredicate, false, iterationType);
3238
+ }
3191
3239
  /**
3192
3240
  * Traverses the tree and returns nodes that are lesser or greater than a target node.
3193
3241
  * @remarks Time O(N), as it performs a full traversal. Space O(log N) or O(N).
@@ -3348,6 +3396,121 @@ var BST = class extends BinaryTree {
3348
3396
  }
3349
3397
  return false;
3350
3398
  }
3399
+ /**
3400
+ * (Protected) Core bound search implementation supporting all parameter types.
3401
+ * Unified logic for both lowerBound and upperBound.
3402
+ * Resolves various input types (Key, Node, Entry, Predicate) using parent class utilities.
3403
+ * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.
3404
+ * @param isLower - True for lowerBound (>=), false for upperBound (>).
3405
+ * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).
3406
+ * @returns The first matching node, or undefined if no such node exists.
3407
+ */
3408
+ _bound(keyNodeEntryOrPredicate, isLower, iterationType) {
3409
+ if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === void 0) {
3410
+ return void 0;
3411
+ }
3412
+ if (this._isPredicate(keyNodeEntryOrPredicate)) {
3413
+ return this._boundByPredicate(keyNodeEntryOrPredicate, iterationType);
3414
+ }
3415
+ let targetKey;
3416
+ if (this.isNode(keyNodeEntryOrPredicate)) {
3417
+ targetKey = keyNodeEntryOrPredicate.key;
3418
+ } else if (this.isEntry(keyNodeEntryOrPredicate)) {
3419
+ const key = keyNodeEntryOrPredicate[0];
3420
+ if (key === null || key === void 0) {
3421
+ return void 0;
3422
+ }
3423
+ targetKey = key;
3424
+ } else {
3425
+ targetKey = keyNodeEntryOrPredicate;
3426
+ }
3427
+ if (targetKey !== void 0) {
3428
+ return this._boundByKey(targetKey, isLower, iterationType);
3429
+ }
3430
+ return void 0;
3431
+ }
3432
+ /**
3433
+ * (Protected) Binary search for bound by key with pruning optimization.
3434
+ * Performs standard BST binary search, choosing left or right subtree based on comparator result.
3435
+ * For lowerBound: finds first node where key >= target.
3436
+ * For upperBound: finds first node where key > target.
3437
+ * @param key - The target key to search for.
3438
+ * @param isLower - True for lowerBound (>=), false for upperBound (>).
3439
+ * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).
3440
+ * @returns The first node matching the bound condition, or undefined if none exists.
3441
+ */
3442
+ _boundByKey(key, isLower, iterationType) {
3443
+ if (iterationType === "RECURSIVE") {
3444
+ const dfs = /* @__PURE__ */ __name((cur) => {
3445
+ if (!this.isRealNode(cur)) return void 0;
3446
+ const cmp = this.comparator(cur.key, key);
3447
+ const condition = isLower ? cmp >= 0 : cmp > 0;
3448
+ if (condition) {
3449
+ const leftResult = dfs(cur.left);
3450
+ return leftResult ?? cur;
3451
+ } else {
3452
+ return dfs(cur.right);
3453
+ }
3454
+ }, "dfs");
3455
+ return dfs(this.root);
3456
+ } else {
3457
+ let current = this.root;
3458
+ let result = void 0;
3459
+ while (this.isRealNode(current)) {
3460
+ const cmp = this.comparator(current.key, key);
3461
+ const condition = isLower ? cmp >= 0 : cmp > 0;
3462
+ if (condition) {
3463
+ result = current;
3464
+ current = current.left ?? void 0;
3465
+ } else {
3466
+ current = current.right ?? void 0;
3467
+ }
3468
+ }
3469
+ return result;
3470
+ }
3471
+ }
3472
+ /**
3473
+ * (Protected) In-order traversal search by predicate.
3474
+ * Falls back to linear in-order traversal when predicate-based search is required.
3475
+ * Returns the first node that satisfies the predicate function.
3476
+ * Note: Predicate-based search cannot leverage BST's binary search optimization.
3477
+ * Time Complexity: O(n) since it may visit every node.
3478
+ * @param predicate - The predicate function to test nodes.
3479
+ * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).
3480
+ * @returns The first node satisfying predicate, or undefined if none found.
3481
+ */
3482
+ _boundByPredicate(predicate, iterationType) {
3483
+ if (iterationType === "RECURSIVE") {
3484
+ let result = void 0;
3485
+ const dfs = /* @__PURE__ */ __name((cur) => {
3486
+ if (result || !this.isRealNode(cur)) return;
3487
+ if (this.isRealNode(cur.left)) dfs(cur.left);
3488
+ if (!result && predicate(cur)) {
3489
+ result = cur;
3490
+ }
3491
+ if (!result && this.isRealNode(cur.right)) dfs(cur.right);
3492
+ }, "dfs");
3493
+ dfs(this.root);
3494
+ return result;
3495
+ } else {
3496
+ const stack = [];
3497
+ let current = this.root;
3498
+ while (stack.length > 0 || this.isRealNode(current)) {
3499
+ if (this.isRealNode(current)) {
3500
+ stack.push(current);
3501
+ current = current.left;
3502
+ } else {
3503
+ const node = stack.pop();
3504
+ if (!this.isRealNode(node)) break;
3505
+ if (predicate(node)) {
3506
+ return node;
3507
+ }
3508
+ current = node.right;
3509
+ }
3510
+ }
3511
+ return void 0;
3512
+ }
3513
+ }
3351
3514
  /**
3352
3515
  * (Protected) Creates a new, empty instance of the same BST constructor.
3353
3516
  * @remarks Time O(1)