data-structure-typed 2.0.4 → 2.0.5

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "data-structure-typed",
3
- "version": "2.0.4",
3
+ "version": "2.0.5",
4
4
  "description": "Standard data structure",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",
@@ -21,10 +21,11 @@ import type {
21
21
  NodePredicate,
22
22
  OptNodeOrNull,
23
23
  RBTNColor,
24
- ToEntryFn
24
+ ToEntryFn,
25
+ Trampoline
25
26
  } from '../../types';
26
27
  import { IBinaryTree } from '../../interfaces';
27
- import { isComparable, trampoline } from '../../utils';
28
+ import { isComparable, makeTrampoline, makeTrampolineThunk } from '../../utils';
28
29
  import { Queue } from '../queue';
29
30
  import { IterableEntryBase } from '../base';
30
31
  import { DFSOperation, Range } from '../../common';
@@ -1294,19 +1295,20 @@ export class BinaryTree<K = any, V = any, R = object, MK = any, MV = any, MR = o
1294
1295
  startNode = this.ensureNode(startNode);
1295
1296
 
1296
1297
  if (!this.isRealNode(startNode)) return callback(startNode);
1297
-
1298
1298
  if (iterationType === 'RECURSIVE') {
1299
1299
  const dfs = (cur: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> => {
1300
- if (!this.isRealNode(cur.left)) return cur;
1301
- return dfs(cur.left);
1300
+ const { left } = cur;
1301
+ if (!this.isRealNode(left)) return cur;
1302
+ return dfs(left);
1302
1303
  };
1303
1304
 
1304
1305
  return callback(dfs(startNode));
1305
1306
  } else {
1306
1307
  // Indirect implementation of iteration using tail recursion optimization
1307
- const dfs = trampoline((cur: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> => {
1308
- if (!this.isRealNode(cur.left)) return cur;
1309
- return dfs.cont(cur.left);
1308
+ const dfs = makeTrampoline((cur: BinaryTreeNode<K, V>): Trampoline<BinaryTreeNode<K, V>> => {
1309
+ const { left } = cur;
1310
+ if (!this.isRealNode(left)) return cur;
1311
+ return makeTrampolineThunk(() => dfs(left));
1310
1312
  });
1311
1313
 
1312
1314
  return callback(dfs(startNode));
@@ -1346,16 +1348,19 @@ export class BinaryTree<K = any, V = any, R = object, MK = any, MV = any, MR = o
1346
1348
 
1347
1349
  if (iterationType === 'RECURSIVE') {
1348
1350
  const dfs = (cur: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> => {
1349
- if (!this.isRealNode(cur.right)) return cur;
1350
- return dfs(cur.right);
1351
+ const { right } = cur;
1352
+ if (!this.isRealNode(right)) return cur;
1353
+ return dfs(right);
1351
1354
  };
1352
1355
 
1353
1356
  return callback(dfs(startNode));
1354
1357
  } else {
1355
1358
  // Indirect implementation of iteration using tail recursion optimization
1356
- const dfs = trampoline((cur: BinaryTreeNode<K, V>) => {
1357
- if (!this.isRealNode(cur.right)) return cur;
1358
- return dfs.cont(cur.right);
1359
+
1360
+ const dfs = makeTrampoline((cur: BinaryTreeNode<K, V>): Trampoline<BinaryTreeNode<K, V>> => {
1361
+ const { right } = cur;
1362
+ if (!this.isRealNode(right)) return cur;
1363
+ return makeTrampolineThunk(() => dfs(right));
1359
1364
  });
1360
1365
 
1361
1366
  return callback(dfs(startNode));
@@ -1,8 +1,3 @@
1
- export type ToThunkFn<R = any> = () => R;
2
- export type Thunk<R = any> = ToThunkFn<R> & { __THUNK__?: symbol };
3
- export type TrlFn<A extends any[] = any[], R = any> = (...args: A) => R;
4
- export type TrlAsyncFn = (...args: any[]) => any;
5
-
6
1
  export type SpecifyOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
7
2
 
8
3
  export type Any = string | number | bigint | boolean | symbol | undefined | object;
@@ -27,3 +22,10 @@ export interface StringComparableObject extends BaseComparableObject {
27
22
  export type ComparableObject = ValueComparableObject | StringComparableObject;
28
23
 
29
24
  export type Comparable = ComparablePrimitive | Date | ComparableObject;
25
+
26
+ export type TrampolineThunk<T> = {
27
+ readonly isThunk: true;
28
+ readonly fn: () => Trampoline<T>;
29
+ };
30
+
31
+ export type Trampoline<T> = T | TrampolineThunk<T>;
@@ -5,7 +5,7 @@
5
5
  * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
6
6
  * @license MIT License
7
7
  */
8
- import type { Comparable, ComparablePrimitive, Thunk, ToThunkFn, TrlAsyncFn, TrlFn } from '../types';
8
+ import type { Comparable, ComparablePrimitive, TrampolineThunk, Trampoline } from '../types';
9
9
 
10
10
  /**
11
11
  * The function generates a random UUID (Universally Unique Identifier) in TypeScript.
@@ -47,91 +47,6 @@ export const arrayRemove = function <T>(array: T[], predicate: (item: T, index:
47
47
  return result;
48
48
  };
49
49
 
50
- export const THUNK_SYMBOL = Symbol('thunk');
51
-
52
- /**
53
- * The function `isThunk` checks if a given value is a function with a specific symbol property.
54
- * @param {any} fnOrValue - The `fnOrValue` parameter in the `isThunk` function can be either a
55
- * function or a value that you want to check if it is a thunk. Thunks are functions that are wrapped
56
- * around a value or computation for lazy evaluation. The function checks if the `fnOrValue` is
57
- * @returns The function `isThunk` is checking if the input `fnOrValue` is a function and if it has a
58
- * property `__THUNK__` equal to `THUNK_SYMBOL`. The return value will be `true` if both conditions are
59
- * met, otherwise it will be `false`.
60
- */
61
- export const isThunk = (fnOrValue: any) => {
62
- return typeof fnOrValue === 'function' && fnOrValue.__THUNK__ === THUNK_SYMBOL;
63
- };
64
-
65
- /**
66
- * The `toThunk` function in TypeScript converts a function into a thunk by wrapping it in a closure.
67
- * @param {ToThunkFn} fn - `fn` is a function that will be converted into a thunk.
68
- * @returns A thunk function is being returned. Thunk functions are functions that delay the evaluation
69
- * of an expression or operation until it is explicitly called or invoked. In this case, the `toThunk`
70
- * function takes a function `fn` as an argument and returns a thunk function that, when called, will
71
- * execute the `fn` function provided as an argument.
72
- */
73
- export const toThunk = (fn: ToThunkFn): Thunk => {
74
- const thunk = () => fn();
75
- thunk.__THUNK__ = THUNK_SYMBOL;
76
- return thunk;
77
- };
78
-
79
- /**
80
- * The `trampoline` function in TypeScript enables tail call optimization by using thunks to avoid
81
- * stack overflow.
82
- * @param {TrlFn} fn - The `fn` parameter in the `trampoline` function is a function that takes any
83
- * number of arguments and returns a value.
84
- * @returns The `trampoline` function returns an object with two properties:
85
- * 1. A function that executes the provided function `fn` and continues to execute any thunks returned
86
- * by `fn` until a non-thunk value is returned.
87
- * 2. A `cont` property that is a function which creates a thunk for the provided function `fn`.
88
- */
89
- export const trampoline = (fn: TrlFn) => {
90
- const cont = (...args: [...Parameters<TrlFn>]): ReturnType<TrlFn> => toThunk(() => fn(...args));
91
-
92
- return Object.assign(
93
- (...args: [...Parameters<TrlFn>]) => {
94
- let result = fn(...args);
95
-
96
- while (isThunk(result) && typeof result === 'function') {
97
- result = result();
98
- }
99
-
100
- return result;
101
- },
102
- { cont }
103
- );
104
- };
105
-
106
- /**
107
- * The `trampolineAsync` function in TypeScript allows for asynchronous trampolining of a given
108
- * function.
109
- * @param {TrlAsyncFn} fn - The `fn` parameter in the `trampolineAsync` function is expected to be a
110
- * function that returns a Promise. This function will be called recursively until a non-thunk value is
111
- * returned.
112
- * @returns The `trampolineAsync` function returns an object with two properties:
113
- * 1. An async function that executes the provided `TrlAsyncFn` function and continues to execute any
114
- * thunks returned by the function until a non-thunk value is returned.
115
- * 2. A `cont` property that is a function which wraps the provided `TrlAsyncFn` function in a thunk
116
- * and returns it.
117
- */
118
- export const trampolineAsync = (fn: TrlAsyncFn) => {
119
- const cont = (...args: [...Parameters<TrlAsyncFn>]): ReturnType<TrlAsyncFn> => toThunk(() => fn(...args));
120
-
121
- return Object.assign(
122
- async (...args: [...Parameters<TrlAsyncFn>]) => {
123
- let result = await fn(...args);
124
-
125
- while (isThunk(result) && typeof result === 'function') {
126
- result = await result();
127
- }
128
-
129
- return result;
130
- },
131
- { cont }
132
- );
133
- };
134
-
135
50
  /**
136
51
  * The function `getMSB` returns the most significant bit of a given number.
137
52
  * @param {number} value - The `value` parameter is a number for which we want to find the position of
@@ -282,3 +197,159 @@ export function isComparable(value: unknown, isForceObjectComparable = false): v
282
197
  if (comparableValue === null || comparableValue === undefined) return false;
283
198
  return isPrimitiveComparable(comparableValue);
284
199
  }
200
+
201
+ /**
202
+ * Creates a trampoline thunk object.
203
+ *
204
+ * A "thunk" is a deferred computation — instead of performing a recursive call immediately,
205
+ * it wraps the next step of the computation in a function. This allows recursive processes
206
+ * to be executed iteratively, preventing stack overflows.
207
+ *
208
+ * @template T - The type of the final computation result.
209
+ * @param computation - A function that, when executed, returns the next trampoline step.
210
+ * @returns A TrampolineThunk object containing the deferred computation.
211
+ */
212
+ export const makeTrampolineThunk = <T>(
213
+ computation: () => Trampoline<T>
214
+ ): TrampolineThunk<T> => ({
215
+ isThunk: true, // Marker indicating this is a thunk
216
+ fn: computation // The deferred computation function
217
+ });
218
+
219
+ /**
220
+ * Type guard to check whether a given value is a TrampolineThunk.
221
+ *
222
+ * This function is used to distinguish between a final computation result (value)
223
+ * and a deferred computation (thunk).
224
+ *
225
+ * @template T - The type of the value being checked.
226
+ * @param value - The value to test.
227
+ * @returns True if the value is a valid TrampolineThunk, false otherwise.
228
+ */
229
+ export const isTrampolineThunk = <T>(
230
+ value: Trampoline<T>
231
+ ): value is TrampolineThunk<T> =>
232
+ typeof value === 'object' && // Must be an object
233
+ value !== null && // Must not be null
234
+ 'isThunk' in value && // Must have the 'isThunk' property
235
+ value.isThunk; // The flag must be true
236
+
237
+ /**
238
+ * Executes a trampoline computation until a final (non-thunk) result is obtained.
239
+ *
240
+ * The trampoline function repeatedly invokes the deferred computations (thunks)
241
+ * in an iterative loop. This avoids deep recursive calls and prevents stack overflow,
242
+ * which is particularly useful for implementing recursion in a stack-safe manner.
243
+ *
244
+ * @template T - The type of the final result.
245
+ * @param initial - The initial Trampoline value or thunk to start execution from.
246
+ * @returns The final result of the computation (a non-thunk value).
247
+ */
248
+ export function trampoline<T>(initial: Trampoline<T>): T {
249
+ let current = initial; // Start with the initial trampoline value
250
+ while (isTrampolineThunk(current)) { // Keep unwrapping while we have thunks
251
+ current = current.fn(); // Execute the deferred function to get the next step
252
+ }
253
+ return current; // Once no thunks remain, return the final result
254
+ }
255
+
256
+ /**
257
+ * Wraps a recursive function inside a trampoline executor.
258
+ *
259
+ * This function transforms a potentially recursive function (that returns a Trampoline<Result>)
260
+ * into a *stack-safe* function that executes iteratively using the `trampoline` runner.
261
+ *
262
+ * In other words, it allows you to write functions that look recursive,
263
+ * but actually run in constant stack space.
264
+ *
265
+ * @template Args - The tuple type representing the argument list of the original function.
266
+ * @template Result - The final return type after all trampoline steps are resolved.
267
+ *
268
+ * @param fn - A function that performs a single step of computation
269
+ * and returns a Trampoline (either a final value or a deferred thunk).
270
+ *
271
+ * @returns A new function with the same arguments, but which automatically
272
+ * runs the trampoline process and returns the *final result* instead
273
+ * of a Trampoline.
274
+ *
275
+ * @example
276
+ * // Example: Computing factorial in a stack-safe way
277
+ * const factorial = makeTrampoline(function fact(n: number, acc: number = 1): Trampoline<number> {
278
+ * return n === 0
279
+ * ? acc
280
+ * : makeTrampolineThunk(() => fact(n - 1, acc * n));
281
+ * });
282
+ *
283
+ * console.log(factorial(100000)); // Works without stack overflow
284
+ */
285
+ export function makeTrampoline<Args extends any[], Result>(
286
+ fn: (...args: Args) => Trampoline<Result> // A function that returns a trampoline step
287
+ ): (...args: Args) => Result {
288
+ // Return a wrapped function that automatically runs the trampoline execution loop
289
+ return (...args: Args) => trampoline(fn(...args));
290
+ }
291
+
292
+ /**
293
+ * Executes an asynchronous trampoline computation until a final (non-thunk) result is obtained.
294
+ *
295
+ * This function repeatedly invokes asynchronous deferred computations (thunks)
296
+ * in an iterative loop. Each thunk may return either a Trampoline<T> or a Promise<Trampoline<T>>.
297
+ *
298
+ * It ensures that asynchronous recursive functions can run without growing the call stack,
299
+ * making it suitable for stack-safe async recursion.
300
+ *
301
+ * @template T - The type of the final result.
302
+ * @param initial - The initial Trampoline or Promise of Trampoline to start execution from.
303
+ * @returns A Promise that resolves to the final result (a non-thunk value).
304
+ */
305
+ export async function asyncTrampoline<T>(
306
+ initial: Trampoline<T> | Promise<Trampoline<T>>
307
+ ): Promise<T> {
308
+ let current = await initial; // Wait for the initial step to resolve if it's a Promise
309
+
310
+ // Keep executing thunks until we reach a non-thunk (final) value
311
+ while (isTrampolineThunk(current)) {
312
+ current = await current.fn(); // Execute the thunk function (may be async)
313
+ }
314
+
315
+ // Once the final value is reached, return it
316
+ return current;
317
+ }
318
+
319
+ /**
320
+ * Wraps an asynchronous recursive function inside an async trampoline executor.
321
+ *
322
+ * This helper transforms a recursive async function that returns a Trampoline<Result>
323
+ * (or Promise<Trampoline<Result>>) into a *stack-safe* async function that executes
324
+ * iteratively via the `asyncTrampoline` runner.
325
+ *
326
+ * @template Args - The tuple type representing the argument list of the original function.
327
+ * @template Result - The final return type after all async trampoline steps are resolved.
328
+ *
329
+ * @param fn - An async or sync function that performs a single step of computation
330
+ * and returns a Trampoline (either a final value or a deferred thunk).
331
+ *
332
+ * @returns An async function with the same arguments, but which automatically
333
+ * runs the trampoline process and resolves to the *final result*.
334
+ *
335
+ * @example
336
+ * // Example: Async factorial using trampoline
337
+ * const asyncFactorial = makeAsyncTrampoline(async function fact(
338
+ * n: number,
339
+ * acc: number = 1
340
+ * ): Promise<Trampoline<number>> {
341
+ * return n === 0
342
+ * ? acc
343
+ * : makeTrampolineThunk(() => fact(n - 1, acc * n));
344
+ * });
345
+ *
346
+ * asyncFactorial(100000).then(console.log); // Works without stack overflow
347
+ */
348
+ export function makeAsyncTrampoline<Args extends any[], Result>(
349
+ fn: (...args: Args) => Trampoline<Result> | Promise<Trampoline<Result>>
350
+ ): (...args: Args) => Promise<Result> {
351
+ // Return a wrapped async function that runs through the async trampoline loop
352
+ return async (...args: Args): Promise<Result> => {
353
+ return asyncTrampoline(fn(...args));
354
+ };
355
+ }
@@ -1537,6 +1537,82 @@ describe('BST iterative methods not map mode test', () => {
1537
1537
  });
1538
1538
  });
1539
1539
 
1540
+ describe('BST constructor and comparator edge cases', () => {
1541
+ it('should support specifyComparable and isReverse', () => {
1542
+ const bst = new BST<number>([], {
1543
+ specifyComparable: (k) => -k,
1544
+ isReverse: true
1545
+ });
1546
+ bst.add(1);
1547
+ bst.add(2);
1548
+ expect(bst.isReverse).toBe(true);
1549
+ expect(bst["_specifyComparable"]).toBeDefined();
1550
+ expect([...bst.keys()]).toEqual([2, 1]);
1551
+ });
1552
+
1553
+ it('should throw if compare object key without specifyComparable', () => {
1554
+ const bst = new BST<any>();
1555
+ expect(() => bst.comparator({ a: 1 }, { a: 2 })).toThrow();
1556
+ });
1557
+ });
1558
+
1559
+ describe('BST addMany edge cases', () => {
1560
+ it('should addMany with values iterable', () => {
1561
+ const bst = new BST<number, string>();
1562
+ const keys = [1, 2, 3];
1563
+ const values = ['a', 'b', 'c'];
1564
+ const result = bst.addMany(keys, values);
1565
+ expect(result).toEqual([true, true, true]);
1566
+ expect([...bst]).toEqual([[1, 'a'], [2, 'b'], [3, 'c']]);
1567
+ });
1568
+
1569
+ it('should addMany with isBalanceAdd=false', () => {
1570
+ const bst = new BST<number>();
1571
+ const result = bst.addMany([3, 1, 2], undefined, false);
1572
+ expect(result).toEqual([true, true, true]);
1573
+ expect([...bst.keys()]).toEqual([1, 2, 3]);
1574
+ });
1575
+
1576
+ it('should addMany with raw/entry/node', () => {
1577
+ const bst = new BST<number, string>([], { isMapMode: false });
1578
+ const node = new BSTNode(5, 'x');
1579
+ const result = bst.addMany([1, [2, 'b'], node]);
1580
+ expect(result).toEqual([true, true, true]);
1581
+ expect(bst.get(5)).toBe('x');
1582
+ });
1583
+ });
1584
+
1585
+ describe('BST perfectlyBalance and isAVLBalanced edge cases', () => {
1586
+ it('should perfectlyBalance with <1 node and both iterationType', () => {
1587
+ const bst = new BST<number>();
1588
+ expect(bst.perfectlyBalance('RECURSIVE')).toBe(false);
1589
+ expect(bst.perfectlyBalance('ITERATIVE')).toBe(false);
1590
+ bst.addMany([1, 2, 3]);
1591
+ expect(bst.perfectlyBalance('RECURSIVE')).toBe(true);
1592
+ bst.clear();
1593
+ bst.addMany([1, 2, 3]);
1594
+ expect(bst.perfectlyBalance('ITERATIVE')).toBe(true);
1595
+ });
1596
+
1597
+ it('should isAVLBalanced with both iterationType', () => {
1598
+ const bst = new BST<number>();
1599
+ expect(bst.isAVLBalanced('RECURSIVE')).toBe(true);
1600
+ expect(bst.isAVLBalanced('ITERATIVE')).toBe(true);
1601
+ bst.addMany([1, 2, 3, 4, 5]);
1602
+ expect(typeof bst.isAVLBalanced('RECURSIVE')).toBe('boolean');
1603
+ expect(typeof bst.isAVLBalanced('ITERATIVE')).toBe('boolean');
1604
+ });
1605
+ });
1606
+
1607
+ describe('BST _keyValueNodeOrEntryToNodeAndValue edge', () => {
1608
+ it('should return [undefined, undefined] for null', () => {
1609
+ const bst = new BST<number>();
1610
+ // @ts-ignore
1611
+ const result = bst["_keyValueNodeOrEntryToNodeAndValue"](null);
1612
+ expect(result).toEqual([undefined, undefined]);
1613
+ });
1614
+ });
1615
+
1540
1616
  describe('classic use', () => {
1541
1617
  it('@example Merge 3 sorted datasets', () => {
1542
1618
  const dataset1 = new BST<number, string>([