@catbee/utils 0.0.1

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 (183) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +295 -0
  3. package/build/esm/config.d.ts +22 -0
  4. package/build/esm/config.js +21 -0
  5. package/build/esm/config.js.map +1 -0
  6. package/build/esm/index.d.ts +19 -0
  7. package/build/esm/index.js +19 -0
  8. package/build/esm/index.js.map +1 -0
  9. package/build/esm/types/api-response.d.ts +44 -0
  10. package/build/esm/types/api-response.js +2 -0
  11. package/build/esm/types/api-response.js.map +1 -0
  12. package/build/esm/utils/array.utils.d.ts +105 -0
  13. package/build/esm/utils/array.utils.js +232 -0
  14. package/build/esm/utils/array.utils.js.map +1 -0
  15. package/build/esm/utils/async.utils.d.ts +119 -0
  16. package/build/esm/utils/async.utils.js +474 -0
  17. package/build/esm/utils/async.utils.js.map +1 -0
  18. package/build/esm/utils/cache.utils.d.ts +90 -0
  19. package/build/esm/utils/cache.utils.js +294 -0
  20. package/build/esm/utils/cache.utils.js.map +1 -0
  21. package/build/esm/utils/context-store.utils.d.ts +85 -0
  22. package/build/esm/utils/context-store.utils.js +99 -0
  23. package/build/esm/utils/context-store.utils.js.map +1 -0
  24. package/build/esm/utils/crypto.utils.d.ts +58 -0
  25. package/build/esm/utils/crypto.utils.js +76 -0
  26. package/build/esm/utils/crypto.utils.js.map +1 -0
  27. package/build/esm/utils/dir.utils.d.ts +75 -0
  28. package/build/esm/utils/dir.utils.js +400 -0
  29. package/build/esm/utils/dir.utils.js.map +1 -0
  30. package/build/esm/utils/env.utils.d.ts +131 -0
  31. package/build/esm/utils/env.utils.js +218 -0
  32. package/build/esm/utils/env.utils.js.map +1 -0
  33. package/build/esm/utils/exception.utils.d.ts +114 -0
  34. package/build/esm/utils/exception.utils.js +217 -0
  35. package/build/esm/utils/exception.utils.js.map +1 -0
  36. package/build/esm/utils/fs.utils.d.ts +32 -0
  37. package/build/esm/utils/fs.utils.js +140 -0
  38. package/build/esm/utils/fs.utils.js.map +1 -0
  39. package/build/esm/utils/http-status-codes.d.ts +357 -0
  40. package/build/esm/utils/http-status-codes.js +358 -0
  41. package/build/esm/utils/http-status-codes.js.map +1 -0
  42. package/build/esm/utils/id.utils.d.ts +35 -0
  43. package/build/esm/utils/id.utils.js +55 -0
  44. package/build/esm/utils/id.utils.js.map +1 -0
  45. package/build/esm/utils/logger.utils.d.ts +15 -0
  46. package/build/esm/utils/logger.utils.js +59 -0
  47. package/build/esm/utils/logger.utils.js.map +1 -0
  48. package/build/esm/utils/obj.utils.d.ts +55 -0
  49. package/build/esm/utils/obj.utils.js +121 -0
  50. package/build/esm/utils/obj.utils.js.map +1 -0
  51. package/build/esm/utils/response.utils.d.ts +48 -0
  52. package/build/esm/utils/response.utils.js +80 -0
  53. package/build/esm/utils/response.utils.js.map +1 -0
  54. package/build/esm/utils/string.utils.d.ts +37 -0
  55. package/build/esm/utils/string.utils.js +56 -0
  56. package/build/esm/utils/string.utils.js.map +1 -0
  57. package/build/esm/utils/url.utils.d.ts +24 -0
  58. package/build/esm/utils/url.utils.js +73 -0
  59. package/build/esm/utils/url.utils.js.map +1 -0
  60. package/build/esm/utils/validate.utils.d.ts +60 -0
  61. package/build/esm/utils/validate.utils.js +121 -0
  62. package/build/esm/utils/validate.utils.js.map +1 -0
  63. package/build/esnext/config.d.ts +22 -0
  64. package/build/esnext/config.js +21 -0
  65. package/build/esnext/config.js.map +1 -0
  66. package/build/esnext/index.d.ts +19 -0
  67. package/build/esnext/index.js +19 -0
  68. package/build/esnext/index.js.map +1 -0
  69. package/build/esnext/types/api-response.d.ts +44 -0
  70. package/build/esnext/types/api-response.js +2 -0
  71. package/build/esnext/types/api-response.js.map +1 -0
  72. package/build/esnext/utils/array.utils.d.ts +105 -0
  73. package/build/esnext/utils/array.utils.js +203 -0
  74. package/build/esnext/utils/array.utils.js.map +1 -0
  75. package/build/esnext/utils/async.utils.d.ts +119 -0
  76. package/build/esnext/utils/async.utils.js +291 -0
  77. package/build/esnext/utils/async.utils.js.map +1 -0
  78. package/build/esnext/utils/cache.utils.d.ts +90 -0
  79. package/build/esnext/utils/cache.utils.js +142 -0
  80. package/build/esnext/utils/cache.utils.js.map +1 -0
  81. package/build/esnext/utils/context-store.utils.d.ts +85 -0
  82. package/build/esnext/utils/context-store.utils.js +95 -0
  83. package/build/esnext/utils/context-store.utils.js.map +1 -0
  84. package/build/esnext/utils/crypto.utils.d.ts +58 -0
  85. package/build/esnext/utils/crypto.utils.js +72 -0
  86. package/build/esnext/utils/crypto.utils.js.map +1 -0
  87. package/build/esnext/utils/dir.utils.d.ts +75 -0
  88. package/build/esnext/utils/dir.utils.js +150 -0
  89. package/build/esnext/utils/dir.utils.js.map +1 -0
  90. package/build/esnext/utils/env.utils.d.ts +131 -0
  91. package/build/esnext/utils/env.utils.js +211 -0
  92. package/build/esnext/utils/env.utils.js.map +1 -0
  93. package/build/esnext/utils/exception.utils.d.ts +114 -0
  94. package/build/esnext/utils/exception.utils.js +148 -0
  95. package/build/esnext/utils/exception.utils.js.map +1 -0
  96. package/build/esnext/utils/fs.utils.d.ts +32 -0
  97. package/build/esnext/utils/fs.utils.js +62 -0
  98. package/build/esnext/utils/fs.utils.js.map +1 -0
  99. package/build/esnext/utils/http-status-codes.d.ts +357 -0
  100. package/build/esnext/utils/http-status-codes.js +358 -0
  101. package/build/esnext/utils/http-status-codes.js.map +1 -0
  102. package/build/esnext/utils/id.utils.d.ts +35 -0
  103. package/build/esnext/utils/id.utils.js +53 -0
  104. package/build/esnext/utils/id.utils.js.map +1 -0
  105. package/build/esnext/utils/logger.utils.d.ts +15 -0
  106. package/build/esnext/utils/logger.utils.js +59 -0
  107. package/build/esnext/utils/logger.utils.js.map +1 -0
  108. package/build/esnext/utils/obj.utils.d.ts +55 -0
  109. package/build/esnext/utils/obj.utils.js +94 -0
  110. package/build/esnext/utils/obj.utils.js.map +1 -0
  111. package/build/esnext/utils/response.utils.d.ts +48 -0
  112. package/build/esnext/utils/response.utils.js +58 -0
  113. package/build/esnext/utils/response.utils.js.map +1 -0
  114. package/build/esnext/utils/string.utils.d.ts +37 -0
  115. package/build/esnext/utils/string.utils.js +46 -0
  116. package/build/esnext/utils/string.utils.js.map +1 -0
  117. package/build/esnext/utils/url.utils.d.ts +24 -0
  118. package/build/esnext/utils/url.utils.js +35 -0
  119. package/build/esnext/utils/url.utils.js.map +1 -0
  120. package/build/esnext/utils/validate.utils.d.ts +60 -0
  121. package/build/esnext/utils/validate.utils.js +105 -0
  122. package/build/esnext/utils/validate.utils.js.map +1 -0
  123. package/build/src/config.d.ts +22 -0
  124. package/build/src/config.js +24 -0
  125. package/build/src/config.js.map +1 -0
  126. package/build/src/index.d.ts +19 -0
  127. package/build/src/index.js +35 -0
  128. package/build/src/index.js.map +1 -0
  129. package/build/src/types/api-response.d.ts +44 -0
  130. package/build/src/types/api-response.js +3 -0
  131. package/build/src/types/api-response.js.map +1 -0
  132. package/build/src/utils/array.utils.d.ts +105 -0
  133. package/build/src/utils/array.utils.js +216 -0
  134. package/build/src/utils/array.utils.js.map +1 -0
  135. package/build/src/utils/async.utils.d.ts +119 -0
  136. package/build/src/utils/async.utils.js +304 -0
  137. package/build/src/utils/async.utils.js.map +1 -0
  138. package/build/src/utils/cache.utils.d.ts +90 -0
  139. package/build/src/utils/cache.utils.js +146 -0
  140. package/build/src/utils/cache.utils.js.map +1 -0
  141. package/build/src/utils/context-store.utils.d.ts +85 -0
  142. package/build/src/utils/context-store.utils.js +100 -0
  143. package/build/src/utils/context-store.utils.js.map +1 -0
  144. package/build/src/utils/crypto.utils.d.ts +58 -0
  145. package/build/src/utils/crypto.utils.js +82 -0
  146. package/build/src/utils/crypto.utils.js.map +1 -0
  147. package/build/src/utils/dir.utils.d.ts +75 -0
  148. package/build/src/utils/dir.utils.js +164 -0
  149. package/build/src/utils/dir.utils.js.map +1 -0
  150. package/build/src/utils/env.utils.d.ts +131 -0
  151. package/build/src/utils/env.utils.js +215 -0
  152. package/build/src/utils/env.utils.js.map +1 -0
  153. package/build/src/utils/exception.utils.d.ts +114 -0
  154. package/build/src/utils/exception.utils.js +162 -0
  155. package/build/src/utils/exception.utils.js.map +1 -0
  156. package/build/src/utils/fs.utils.d.ts +32 -0
  157. package/build/src/utils/fs.utils.js +71 -0
  158. package/build/src/utils/fs.utils.js.map +1 -0
  159. package/build/src/utils/http-status-codes.d.ts +357 -0
  160. package/build/src/utils/http-status-codes.js +361 -0
  161. package/build/src/utils/http-status-codes.js.map +1 -0
  162. package/build/src/utils/id.utils.d.ts +35 -0
  163. package/build/src/utils/id.utils.js +60 -0
  164. package/build/src/utils/id.utils.js.map +1 -0
  165. package/build/src/utils/logger.utils.d.ts +15 -0
  166. package/build/src/utils/logger.utils.js +96 -0
  167. package/build/src/utils/logger.utils.js.map +1 -0
  168. package/build/src/utils/obj.utils.d.ts +55 -0
  169. package/build/src/utils/obj.utils.js +103 -0
  170. package/build/src/utils/obj.utils.js.map +1 -0
  171. package/build/src/utils/response.utils.d.ts +48 -0
  172. package/build/src/utils/response.utils.js +63 -0
  173. package/build/src/utils/response.utils.js.map +1 -0
  174. package/build/src/utils/string.utils.d.ts +37 -0
  175. package/build/src/utils/string.utils.js +54 -0
  176. package/build/src/utils/string.utils.js.map +1 -0
  177. package/build/src/utils/url.utils.d.ts +24 -0
  178. package/build/src/utils/url.utils.js +39 -0
  179. package/build/src/utils/url.utils.js.map +1 -0
  180. package/build/src/utils/validate.utils.d.ts +60 -0
  181. package/build/src/utils/validate.utils.js +115 -0
  182. package/build/src/utils/validate.utils.js.map +1 -0
  183. package/package.json +80 -0
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./utils/array.utils"), exports);
18
+ __exportStar(require("./utils/async.utils"), exports);
19
+ __exportStar(require("./utils/cache.utils"), exports);
20
+ __exportStar(require("./utils/context-store.utils"), exports);
21
+ __exportStar(require("./utils/crypto.utils"), exports);
22
+ __exportStar(require("./utils/dir.utils"), exports);
23
+ __exportStar(require("./utils/env.utils"), exports);
24
+ __exportStar(require("./utils/exception.utils"), exports);
25
+ __exportStar(require("./utils/fs.utils"), exports);
26
+ __exportStar(require("./utils/http-status-codes"), exports);
27
+ __exportStar(require("./utils/id.utils"), exports);
28
+ __exportStar(require("./utils/logger.utils"), exports);
29
+ __exportStar(require("./utils/obj.utils"), exports);
30
+ __exportStar(require("./utils/response.utils"), exports);
31
+ __exportStar(require("./utils/string.utils"), exports);
32
+ __exportStar(require("./utils/url.utils"), exports);
33
+ __exportStar(require("./utils/validate.utils"), exports);
34
+ __exportStar(require("./types/api-response"), exports);
35
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,sDAAoC;AACpC,sDAAoC;AACpC,sDAAoC;AACpC,8DAA4C;AAC5C,uDAAqC;AACrC,oDAAkC;AAClC,oDAAkC;AAClC,0DAAwC;AACxC,mDAAiC;AACjC,4DAA0C;AAC1C,mDAAiC;AACjC,uDAAqC;AACrC,oDAAkC;AAClC,yDAAuC;AACvC,uDAAqC;AACrC,oDAAkC;AAClC,yDAAuC;AAEvC,uDAAqC","sourcesContent":["export * from \"./utils/array.utils\";\nexport * from \"./utils/async.utils\";\nexport * from \"./utils/cache.utils\";\nexport * from \"./utils/context-store.utils\";\nexport * from \"./utils/crypto.utils\";\nexport * from \"./utils/dir.utils\";\nexport * from \"./utils/env.utils\";\nexport * from \"./utils/exception.utils\";\nexport * from \"./utils/fs.utils\";\nexport * from \"./utils/http-status-codes\";\nexport * from \"./utils/id.utils\";\nexport * from \"./utils/logger.utils\";\nexport * from \"./utils/obj.utils\";\nexport * from \"./utils/response.utils\";\nexport * from \"./utils/string.utils\";\nexport * from \"./utils/url.utils\";\nexport * from \"./utils/validate.utils\";\n\nexport * from \"./types/api-response\";\n"]}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Generic API response format.
3
+ * Used to wrap any successful or failed response from the server.
4
+ */
5
+ export interface ApiResponse<T = any> {
6
+ /** Payload returned from the API. Can be any shape depending on the endpoint. */
7
+ data: T | null;
8
+ /** Indicates whether an error occurred (true = error, false = success). */
9
+ error: boolean;
10
+ /** Human-readable message to describe the result or error. */
11
+ message: string;
12
+ /** Unique request ID for traceability in logs (e.g., from a middleware). */
13
+ requestId: string;
14
+ /** ISO timestamp when the response was generated. */
15
+ timestamp: string;
16
+ }
17
+ /**
18
+ * Generic pagination structure used for paged lists (e.g., /users?page=1).
19
+ */
20
+ export interface Pagination<T = any> {
21
+ /** List of records for the current page. */
22
+ content: T[];
23
+ /** Metadata about the pagination state. */
24
+ pagination: {
25
+ /** Total number of records across all pages. */
26
+ totalRecords: number;
27
+ /** Total number of pages available. */
28
+ totalPages: number;
29
+ /** Current page number (1-based index). */
30
+ page: number;
31
+ /** Number of records per page. */
32
+ limit: number;
33
+ /** Field by which the data is sorted. */
34
+ sortBy: string;
35
+ /** Sort order: ascending or descending. */
36
+ sortOrder: "asc" | "desc";
37
+ };
38
+ }
39
+ /**
40
+ * Alias for paginated API response.
41
+ * Allows semantic naming like `PaginationResponse<User>` or `PaginationResponse<Post>`.
42
+ */
43
+ export type PaginationResponse<T = any> = Pagination<T>;
44
+ //# sourceMappingURL=api-response.d.ts.map
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=api-response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-response.js","sourceRoot":"","sources":["../../../src/types/api-response.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Generic API response format.\n * Used to wrap any successful or failed response from the server.\n */\nexport interface ApiResponse<T = any> {\n /** Payload returned from the API. Can be any shape depending on the endpoint. */\n data: T | null;\n\n /** Indicates whether an error occurred (true = error, false = success). */\n error: boolean;\n\n /** Human-readable message to describe the result or error. */\n message: string;\n\n /** Unique request ID for traceability in logs (e.g., from a middleware). */\n requestId: string;\n\n /** ISO timestamp when the response was generated. */\n timestamp: string;\n}\n\n/**\n * Generic pagination structure used for paged lists (e.g., /users?page=1).\n */\nexport interface Pagination<T = any> {\n /** List of records for the current page. */\n content: T[];\n\n /** Metadata about the pagination state. */\n pagination: {\n /** Total number of records across all pages. */\n totalRecords: number;\n\n /** Total number of pages available. */\n totalPages: number;\n\n /** Current page number (1-based index). */\n page: number;\n\n /** Number of records per page. */\n limit: number;\n\n /** Field by which the data is sorted. */\n sortBy: string;\n\n /** Sort order: ascending or descending. */\n sortOrder: \"asc\" | \"desc\";\n };\n}\n\n/**\n * Alias for paginated API response.\n * Allows semantic naming like `PaginationResponse<User>` or `PaginationResponse<Post>`.\n */\nexport type PaginationResponse<T = any> = Pagination<T>;\n"]}
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Splits an array into chunks of the specified size.
3
+ *
4
+ * @template T The type of array elements.
5
+ * @param {T[]} array - The array to split into chunks.
6
+ * @param {number} size - The number of elements per chunk.
7
+ * @returns {T[][]} A new array containing chunked arrays.
8
+ * @throws {TypeError} If array is not an array.
9
+ * @throws {Error} If chunk size is not a positive integer.
10
+ */
11
+ export declare const chunk: <T>(array: T[], size: number) => T[][];
12
+ /**
13
+ * Removes duplicate values from an array.
14
+ * Optionally enforces uniqueness by a key function.
15
+ *
16
+ * @template T The type of array elements.
17
+ * @param {T[]} array - The input array.
18
+ * @param {(item: T) => unknown} [keyFn] - Optional function to determine uniqueness by key.
19
+ * @returns {T[]} A new array with unique values.
20
+ */
21
+ export declare function unique<T>(array: T[], keyFn?: (item: T) => unknown): T[];
22
+ /**
23
+ * Deeply flattens a nested array to a single-level array.
24
+ *
25
+ * @template T The leaf type of array elements.
26
+ * @param {any[]} array - The (possibly deeply nested) input array.
27
+ * @returns {T[]} A deeply flattened array.
28
+ */
29
+ export declare function flattenDeep<T>(array: any[]): T[];
30
+ /**
31
+ * Returns a random element from an array, or undefined if empty.
32
+ *
33
+ * @template T The type of array elements.
34
+ * @param {T[]} array - The input array.
35
+ * @returns {T | undefined} A randomly selected item, or undefined if array is empty or not an array.
36
+ */
37
+ export declare function random<T>(array: T[]): T | undefined;
38
+ /**
39
+ * Groups items in an array by a key or key function.
40
+ *
41
+ * @template T The type of array elements.
42
+ * @overload
43
+ * @param {T[]} array - The array to group.
44
+ * @param {keyof T} key - Property key to group by.
45
+ * @returns {Record<string, T[]>}
46
+ * @overload
47
+ * @param {T[]} array - The array to group.
48
+ * @param {(item: T) => string | number | symbol} keyFn - Function to generate group key from item.
49
+ * @returns {Record<K, T[]>}
50
+ * @param {T[]} array - The array to group.
51
+ * @param {keyof T | ((item: T) => string | number | symbol)} keyOrFn - Property key or key-generating function.
52
+ * @returns {Record<string | number | symbol, T[]>} An object mapping group keys to item arrays.
53
+ */
54
+ export declare function groupBy<T>(array: T[], key: keyof T): Record<string, T[]>;
55
+ export declare function groupBy<T, K extends string | number | symbol>(array: T[], keyFn: (item: T) => K): Record<K, T[]>;
56
+ /**
57
+ * Shuffles an array using the Fisher-Yates algorithm.
58
+ *
59
+ * @template T The type of array elements.
60
+ * @param {T[]} array - The input array.
61
+ * @returns {T[]} A new shuffled array.
62
+ * @throws {TypeError} If array is not an array.
63
+ */
64
+ export declare function shuffle<T>(array: T[]): T[];
65
+ /**
66
+ * Returns an array of property values from an array of objects.
67
+ *
68
+ * @template T The type of array elements.
69
+ * @template K The object property to pluck.
70
+ * @param {T[]} array - The input array.
71
+ * @param {K} key - The property name to pluck.
72
+ * @returns {T[K][]} Array of property values.
73
+ */
74
+ export declare function pluck<T, K extends keyof T>(array: T[], key: K): T[K][];
75
+ /**
76
+ * Returns values in array A that are not in array B.
77
+ *
78
+ * @template T The type of array elements.
79
+ * @param {T[]} a - First array.
80
+ * @param {T[]} b - Second array.
81
+ * @returns {T[]} Elements in A that are not in B.
82
+ */
83
+ export declare function difference<T>(a: T[], b: T[]): T[];
84
+ /**
85
+ * Returns common values between arrays A and B.
86
+ *
87
+ * @template T The type of array elements.
88
+ * @param {T[]} a - First array.
89
+ * @param {T[]} b - Second array.
90
+ * @returns {T[]} Elements that exist in both arrays.
91
+ */
92
+ export declare function intersect<T>(a: T[], b: T[]): T[];
93
+ /**
94
+ * Sorts an array of objects by a nested key using Merge Sort (O(n log n)).
95
+ * Missing/undefined keys are sorted to the "end" (asc) or "start" (desc).
96
+ *
97
+ * @template T The type of array elements (objects).
98
+ * @param {T[]} array - Array of objects to sort.
99
+ * @param {string | ((item: T) => any)} key - Dot-notated key (e.g., "profile.age") or function.
100
+ * @param {"asc" | "desc"} [direction="asc"] - Sort direction: 'asc' or 'desc'.
101
+ * @returns {T[]} A new sorted array.
102
+ * @throws {TypeError} If array is not an array.
103
+ */
104
+ export declare function mergeSort<T>(array: T[], key: string | ((item: T) => any), direction?: "asc" | "desc"): T[];
105
+ //# sourceMappingURL=array.utils.d.ts.map
@@ -0,0 +1,216 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.chunk = void 0;
4
+ exports.unique = unique;
5
+ exports.flattenDeep = flattenDeep;
6
+ exports.random = random;
7
+ exports.groupBy = groupBy;
8
+ exports.shuffle = shuffle;
9
+ exports.pluck = pluck;
10
+ exports.difference = difference;
11
+ exports.intersect = intersect;
12
+ exports.mergeSort = mergeSort;
13
+ const obj_utils_1 = require("./obj.utils");
14
+ /**
15
+ * Splits an array into chunks of the specified size.
16
+ *
17
+ * @template T The type of array elements.
18
+ * @param {T[]} array - The array to split into chunks.
19
+ * @param {number} size - The number of elements per chunk.
20
+ * @returns {T[][]} A new array containing chunked arrays.
21
+ * @throws {TypeError} If array is not an array.
22
+ * @throws {Error} If chunk size is not a positive integer.
23
+ */
24
+ const chunk = (array, size) => {
25
+ if (!Array.isArray(array))
26
+ throw new TypeError("Expected an array");
27
+ if (!array.length)
28
+ return [];
29
+ if (!Number.isInteger(size) || size <= 0)
30
+ throw new Error("Chunk size must be a positive integer");
31
+ return Array.from({ length: Math.ceil(array.length / size) }, (_, i) => array.slice(i * size, i * size + size));
32
+ };
33
+ exports.chunk = chunk;
34
+ /**
35
+ * Removes duplicate values from an array.
36
+ * Optionally enforces uniqueness by a key function.
37
+ *
38
+ * @template T The type of array elements.
39
+ * @param {T[]} array - The input array.
40
+ * @param {(item: T) => unknown} [keyFn] - Optional function to determine uniqueness by key.
41
+ * @returns {T[]} A new array with unique values.
42
+ */
43
+ function unique(array, keyFn) {
44
+ if (!Array.isArray(array) || array.length === 0)
45
+ return [];
46
+ if (!keyFn)
47
+ return Array.from(new Set(array));
48
+ const seen = new Set();
49
+ return array.filter((item) => {
50
+ const key = keyFn(item);
51
+ if (seen.has(key))
52
+ return false;
53
+ seen.add(key);
54
+ return true;
55
+ });
56
+ }
57
+ /**
58
+ * Deeply flattens a nested array to a single-level array.
59
+ *
60
+ * @template T The leaf type of array elements.
61
+ * @param {any[]} array - The (possibly deeply nested) input array.
62
+ * @returns {T[]} A deeply flattened array.
63
+ */
64
+ function flattenDeep(array) {
65
+ if (!Array.isArray(array))
66
+ return [];
67
+ return array.reduce((acc, val) => {
68
+ if (Array.isArray(val)) {
69
+ acc.push(...flattenDeep(val));
70
+ }
71
+ else {
72
+ acc.push(val);
73
+ }
74
+ return acc;
75
+ }, []);
76
+ }
77
+ /**
78
+ * Returns a random element from an array, or undefined if empty.
79
+ *
80
+ * @template T The type of array elements.
81
+ * @param {T[]} array - The input array.
82
+ * @returns {T | undefined} A randomly selected item, or undefined if array is empty or not an array.
83
+ */
84
+ function random(array) {
85
+ if (!Array.isArray(array) || array.length === 0)
86
+ return undefined;
87
+ return array[Math.floor(Math.random() * array.length)];
88
+ }
89
+ function groupBy(array, keyOrFn) {
90
+ if (!Array.isArray(array) || array.length === 0)
91
+ return {};
92
+ const keyFn = typeof keyOrFn === "function"
93
+ ? keyOrFn
94
+ : (item) => item[keyOrFn];
95
+ return array.reduce((acc, item) => {
96
+ const key = keyFn(item);
97
+ if (!acc[key])
98
+ acc[key] = [];
99
+ acc[key].push(item);
100
+ return acc;
101
+ }, {});
102
+ }
103
+ /* eslint-enable no-redeclare */
104
+ /**
105
+ * Shuffles an array using the Fisher-Yates algorithm.
106
+ *
107
+ * @template T The type of array elements.
108
+ * @param {T[]} array - The input array.
109
+ * @returns {T[]} A new shuffled array.
110
+ * @throws {TypeError} If array is not an array.
111
+ */
112
+ function shuffle(array) {
113
+ if (!Array.isArray(array))
114
+ throw new TypeError("Expected an array");
115
+ const copy = array.slice();
116
+ for (let i = copy.length - 1; i > 0; i--) {
117
+ const j = Math.floor(Math.random() * (i + 1));
118
+ [copy[i], copy[j]] = [copy[j], copy[i]];
119
+ }
120
+ return copy;
121
+ }
122
+ /**
123
+ * Returns an array of property values from an array of objects.
124
+ *
125
+ * @template T The type of array elements.
126
+ * @template K The object property to pluck.
127
+ * @param {T[]} array - The input array.
128
+ * @param {K} key - The property name to pluck.
129
+ * @returns {T[K][]} Array of property values.
130
+ */
131
+ function pluck(array, key) {
132
+ if (!Array.isArray(array))
133
+ return [];
134
+ return array.map((item) => item[key]);
135
+ }
136
+ /**
137
+ * Returns values in array A that are not in array B.
138
+ *
139
+ * @template T The type of array elements.
140
+ * @param {T[]} a - First array.
141
+ * @param {T[]} b - Second array.
142
+ * @returns {T[]} Elements in A that are not in B.
143
+ */
144
+ function difference(a, b) {
145
+ if (!Array.isArray(a) || !Array.isArray(b))
146
+ return [];
147
+ const setB = new Set(b);
148
+ return a.filter((item) => !setB.has(item));
149
+ }
150
+ /**
151
+ * Returns common values between arrays A and B.
152
+ *
153
+ * @template T The type of array elements.
154
+ * @param {T[]} a - First array.
155
+ * @param {T[]} b - Second array.
156
+ * @returns {T[]} Elements that exist in both arrays.
157
+ */
158
+ function intersect(a, b) {
159
+ if (!Array.isArray(a) || !Array.isArray(b))
160
+ return [];
161
+ const setB = new Set(b);
162
+ return a.filter((item) => setB.has(item));
163
+ }
164
+ /**
165
+ * Sorts an array of objects by a nested key using Merge Sort (O(n log n)).
166
+ * Missing/undefined keys are sorted to the "end" (asc) or "start" (desc).
167
+ *
168
+ * @template T The type of array elements (objects).
169
+ * @param {T[]} array - Array of objects to sort.
170
+ * @param {string | ((item: T) => any)} key - Dot-notated key (e.g., "profile.age") or function.
171
+ * @param {"asc" | "desc"} [direction="asc"] - Sort direction: 'asc' or 'desc'.
172
+ * @returns {T[]} A new sorted array.
173
+ * @throws {TypeError} If array is not an array.
174
+ */
175
+ function mergeSort(array, key, direction = "asc") {
176
+ if (!Array.isArray(array))
177
+ throw new TypeError("Expected array");
178
+ if (array.length <= 1)
179
+ return array.slice();
180
+ const keyFn = typeof key === "function"
181
+ ? key
182
+ : (item) => (0, obj_utils_1.getValueByPath)(item, key);
183
+ const compare = (a, b) => {
184
+ const aVal = keyFn(a);
185
+ const bVal = keyFn(b);
186
+ // Sorts undefined/null last for "asc", first for "desc"
187
+ if (aVal === bVal)
188
+ return 0;
189
+ if (aVal == null)
190
+ return direction === "asc" ? 1 : -1;
191
+ if (bVal == null)
192
+ return direction === "asc" ? -1 : 1;
193
+ return direction === "asc" ? (aVal < bVal ? -1 : 1) : aVal > bVal ? -1 : 1;
194
+ };
195
+ const merge = (left, right) => {
196
+ const result = [];
197
+ let i = 0, j = 0;
198
+ while (i < left.length && j < right.length) {
199
+ if (compare(left[i], right[j]) <= 0)
200
+ result.push(left[i++]);
201
+ else
202
+ result.push(right[j++]);
203
+ }
204
+ return result.concat(left.slice(i)).concat(right.slice(j));
205
+ };
206
+ const sort = (arr) => {
207
+ if (arr.length <= 1)
208
+ return arr;
209
+ const mid = Math.floor(arr.length / 2);
210
+ const left = sort(arr.slice(0, mid));
211
+ const right = sort(arr.slice(mid));
212
+ return merge(left, right);
213
+ };
214
+ return sort(array);
215
+ }
216
+ //# sourceMappingURL=array.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"array.utils.js","sourceRoot":"","sources":["../../../src/utils/array.utils.ts"],"names":[],"mappings":";;;AA+BA,wBAUC;AASD,kCAUC;AASD,wBAGC;AAwBD,0BAkBC;AAWD,0BAQC;AAWD,sBAGC;AAUD,gCAIC;AAUD,8BAIC;AAaD,8BA0CC;AAtOD,2CAA6C;AAE7C;;;;;;;;;GASG;AACI,MAAM,KAAK,GAAG,CAAI,KAAU,EAAE,IAAY,EAAS,EAAE;IAC1D,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,SAAS,CAAC,mBAAmB,CAAC,CAAC;IACpE,IAAI,CAAC,KAAK,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IAC7B,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC;QACtC,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAC3D,OAAO,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACrE,KAAK,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC,CACvC,CAAC;AACJ,CAAC,CAAC;AARW,QAAA,KAAK,SAQhB;AAEF;;;;;;;;GAQG;AACH,SAAgB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E;QAC3C,MAAM,MAAM,GAAQ,EAAE,CAAC;QACvB,IAAI,CAAC,GAAG,CAAC,EACP,CAAC,GAAG,CAAC,CAAC;QACR,OAAO,CAAC,GAAG,IAAI,CAAC,MAAM,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC;YAC3C,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;gBAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;;gBACvD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QAC/B,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7D,CAAC,CAAC;IAEF,MAAM,IAAI,GAAG,CAAC,GAAQ,EAAO,EAAE;QAC7B,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC;YAAE,OAAO,GAAG,CAAC;QAChC,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QACvC,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;QACrC,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;QACnC,OAAO,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC5B,CAAC,CAAC;IACF,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC;AACrB,CAAC","sourcesContent":["import { getValueByPath } from \"./obj.utils\";\n\n/**\n * Splits an array into chunks of the specified size.\n *\n * @template T The type of array elements.\n * @param {T[]} array - The array to split into chunks.\n * @param {number} size - The number of elements per chunk.\n * @returns {T[][]} A new array containing chunked arrays.\n * @throws {TypeError} If array is not an array.\n * @throws {Error} If chunk size is not a positive integer.\n */\nexport const chunk = <T>(array: T[], size: number): T[][] => {\n if (!Array.isArray(array)) throw new TypeError(\"Expected an array\");\n if (!array.length) return [];\n if (!Number.isInteger(size) || size <= 0)\n throw new Error(\"Chunk size must be a positive integer\");\n return Array.from({ length: Math.ceil(array.length / size) }, (_, i) =>\n array.slice(i * size, i * size + size),\n );\n};\n\n/**\n * Removes duplicate values from an array.\n * Optionally enforces uniqueness by a key function.\n *\n * @template T The type of array elements.\n * @param {T[]} array - The input array.\n * @param {(item: T) => unknown} [keyFn] - Optional function to determine uniqueness by key.\n * @returns {T[]} A new array with unique values.\n */\nexport function unique<T>(array: T[], keyFn?: (item: T) => unknown): T[] {\n if (!Array.isArray(array) || array.length === 0) return [];\n if (!keyFn) return Array.from(new Set(array));\n const seen = new Set<unknown>();\n return array.filter((item) => {\n const key = keyFn(item);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/**\n * Deeply flattens a nested array to a single-level array.\n *\n * @template T The leaf type of array elements.\n * @param {any[]} array - The (possibly deeply nested) input array.\n * @returns {T[]} A deeply flattened array.\n */\nexport function flattenDeep<T>(array: any[]): T[] {\n if (!Array.isArray(array)) return [];\n return array.reduce<T[]>((acc, val) => {\n if (Array.isArray(val)) {\n acc.push(...flattenDeep<T>(val));\n } else {\n acc.push(val);\n }\n return acc;\n }, []);\n}\n\n/**\n * Returns a random element from an array, or undefined if empty.\n *\n * @template T The type of array elements.\n * @param {T[]} array - The input array.\n * @returns {T | undefined} A randomly selected item, or undefined if array is empty or not an array.\n */\nexport function random<T>(array: T[]): T | undefined {\n if (!Array.isArray(array) || array.length === 0) return undefined;\n return array[Math.floor(Math.random() * array.length)];\n}\n\n/* eslint-disable no-redeclare */\n/**\n * Groups items in an array by a key or key function.\n *\n * @template T The type of array elements.\n * @overload\n * @param {T[]} array - The array to group.\n * @param {keyof T} key - Property key to group by.\n * @returns {Record<string, T[]>}\n * @overload\n * @param {T[]} array - The array to group.\n * @param {(item: T) => string | number | symbol} keyFn - Function to generate group key from item.\n * @returns {Record<K, T[]>}\n * @param {T[]} array - The array to group.\n * @param {keyof T | ((item: T) => string | number | symbol)} keyOrFn - Property key or key-generating function.\n * @returns {Record<string | number | symbol, T[]>} An object mapping group keys to item arrays.\n */\nexport function groupBy<T>(array: T[], key: keyof T): Record<string, T[]>;\nexport function groupBy<T, K extends string | number | symbol>(\n array: T[],\n keyFn: (item: T) => K,\n): Record<K, T[]>;\nexport function groupBy<T>(\n array: T[],\n keyOrFn: keyof T | ((item: T) => string | number | symbol),\n): Record<string | number | symbol, T[]> {\n if (!Array.isArray(array) || array.length === 0) return {};\n const keyFn =\n typeof keyOrFn === \"function\"\n ? keyOrFn\n : (item: T) => item[keyOrFn as keyof T];\n return array.reduce(\n (acc, item) => {\n const key = keyFn(item) as string | number | symbol;\n if (!acc[key]) acc[key] = [];\n acc[key].push(item);\n return acc;\n },\n {} as Record<string | number | symbol, T[]>,\n );\n}\n/* eslint-enable no-redeclare */\n\n/**\n * Shuffles an array using the Fisher-Yates algorithm.\n *\n * @template T The type of array elements.\n * @param {T[]} array - The input array.\n * @returns {T[]} A new shuffled array.\n * @throws {TypeError} If array is not an array.\n */\nexport function shuffle<T>(array: T[]): T[] {\n if (!Array.isArray(array)) throw new TypeError(\"Expected an array\");\n const copy = array.slice();\n for (let i = copy.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [copy[i], copy[j]] = [copy[j], copy[i]];\n }\n return copy;\n}\n\n/**\n * Returns an array of property values from an array of objects.\n *\n * @template T The type of array elements.\n * @template K The object property to pluck.\n * @param {T[]} array - The input array.\n * @param {K} key - The property name to pluck.\n * @returns {T[K][]} Array of property values.\n */\nexport function pluck<T, K extends keyof T>(array: T[], key: K): T[K][] {\n if (!Array.isArray(array)) return [];\n return array.map((item) => item[key]);\n}\n\n/**\n * Returns values in array A that are not in array B.\n *\n * @template T The type of array elements.\n * @param {T[]} a - First array.\n * @param {T[]} b - Second array.\n * @returns {T[]} Elements in A that are not in B.\n */\nexport function difference<T>(a: T[], b: T[]): T[] {\n if (!Array.isArray(a) || !Array.isArray(b)) return [];\n const setB = new Set(b);\n return a.filter((item) => !setB.has(item));\n}\n\n/**\n * Returns common values between arrays A and B.\n *\n * @template T The type of array elements.\n * @param {T[]} a - First array.\n * @param {T[]} b - Second array.\n * @returns {T[]} Elements that exist in both arrays.\n */\nexport function intersect<T>(a: T[], b: T[]): T[] {\n if (!Array.isArray(a) || !Array.isArray(b)) return [];\n const setB = new Set(b);\n return a.filter((item) => setB.has(item));\n}\n\n/**\n * Sorts an array of objects by a nested key using Merge Sort (O(n log n)).\n * Missing/undefined keys are sorted to the \"end\" (asc) or \"start\" (desc).\n *\n * @template T The type of array elements (objects).\n * @param {T[]} array - Array of objects to sort.\n * @param {string | ((item: T) => any)} key - Dot-notated key (e.g., \"profile.age\") or function.\n * @param {\"asc\" | \"desc\"} [direction=\"asc\"] - Sort direction: 'asc' or 'desc'.\n * @returns {T[]} A new sorted array.\n * @throws {TypeError} If array is not an array.\n */\nexport function mergeSort<T>(\n array: T[],\n key: string | ((item: T) => any),\n direction: \"asc\" | \"desc\" = \"asc\",\n): T[] {\n if (!Array.isArray(array)) throw new TypeError(\"Expected array\");\n if (array.length <= 1) return array.slice();\n\n const keyFn =\n typeof key === \"function\"\n ? key\n : (item: T) => getValueByPath(item as object, key);\n\n const compare = (a: T, b: T) => {\n const aVal = keyFn(a);\n const bVal = keyFn(b);\n // Sorts undefined/null last for \"asc\", first for \"desc\"\n if (aVal === bVal) return 0;\n if (aVal == null) return direction === \"asc\" ? 1 : -1;\n if (bVal == null) return direction === \"asc\" ? -1 : 1;\n return direction === \"asc\" ? (aVal < bVal ? -1 : 1) : aVal > bVal ? -1 : 1;\n };\n\n const merge = (left: T[], right: T[]): T[] => {\n const result: T[] = [];\n let i = 0,\n j = 0;\n while (i < left.length && j < right.length) {\n if (compare(left[i], right[j]) <= 0) result.push(left[i++]);\n else result.push(right[j++]);\n }\n return result.concat(left.slice(i)).concat(right.slice(j));\n };\n\n const sort = (arr: T[]): T[] => {\n if (arr.length <= 1) return arr;\n const mid = Math.floor(arr.length / 2);\n const left = sort(arr.slice(0, mid));\n const right = sort(arr.slice(mid));\n return merge(left, right);\n };\n return sort(array);\n}\n"]}
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Delays execution for a specified number of milliseconds.
3
+ *
4
+ * @param {number} ms - The number of milliseconds to sleep.
5
+ * @returns {Promise<void>} A Promise that resolves after the given time.
6
+ */
7
+ export declare const sleep: (ms: number) => Promise<void>;
8
+ /**
9
+ * Creates a debounced version of a function that delays its execution.
10
+ * Provides `.cancel()` and `.flush()` methods.
11
+ *
12
+ * @template T
13
+ * @param {T} fn - The function to debounce.
14
+ * @param {number} delay - Delay in milliseconds.
15
+ * @returns {T & { cancel: () => void; flush: () => void }} A debounced function.
16
+ */
17
+ export declare function debounce<T extends (...args: any[]) => void>(fn: T, delay: number): {
18
+ (...args: Parameters<T>): void;
19
+ cancel(): void;
20
+ flush(): void;
21
+ } & {
22
+ cancel: () => void;
23
+ flush: () => void;
24
+ };
25
+ /**
26
+ * Creates a throttled version of a function that limits its execution rate.
27
+ * Allows control over leading/trailing invocation.
28
+ *
29
+ * @template T
30
+ * @param {T} fn - The function to throttle.
31
+ * @param {number} limit - Minimum time between calls in milliseconds.
32
+ * @param {{ leading?: boolean, trailing?: boolean }} [opts] - Options for leading/trailing edge throttling.
33
+ * @returns {(...args: Parameters<T>) => void} A throttled function.
34
+ */
35
+ export declare function throttle<T extends (...args: any[]) => void>(fn: T, limit: number, opts?: {
36
+ leading?: boolean;
37
+ trailing?: boolean;
38
+ }): (...args: Parameters<T>) => void;
39
+ /**
40
+ * Retries an asynchronous function a given number of times with optional delay/backoff.
41
+ *
42
+ * @template T
43
+ * @param {() => Promise<T>} fn - The async function to retry.
44
+ * @param {number} [retries=3] - Number of retry attempts.
45
+ * @param {number} [delay=500] - Delay in milliseconds between retries.
46
+ * @param {boolean} [backoff=false] - Use exponential backoff between attempts.
47
+ * @param {(error: unknown, attempt: number) => void} [onRetry] - Callback for each retry attempt.
48
+ * @returns {Promise<T>} The result of the async function if successful.
49
+ * @throws {*} The last encountered error if all retries fail.
50
+ */
51
+ export declare function retry<T>(fn: () => Promise<T>, retries?: number, delay?: number, backoff?: boolean, onRetry?: (error: unknown, attempt: number) => void): Promise<T>;
52
+ /**
53
+ * Wraps a promise and rejects it if it doesn't resolve within the specified timeout.
54
+ *
55
+ * @template T
56
+ * @param {Promise<T>} promise - The original promise.
57
+ * @param {number} ms - Timeout in milliseconds.
58
+ * @param {string} [message="Operation timed out"] - Optional timeout message.
59
+ * @returns {Promise<T>} A promise that resolves or rejects within the timeout.
60
+ */
61
+ export declare function withTimeout<T>(promise: Promise<T>, ms: number, message?: string): Promise<T>;
62
+ /**
63
+ * Executes async tasks in true batches.
64
+ * Each batch runs in parallel, but batches run sequentially.
65
+ * All tasks in a batch start at the same time, next batch waits for full completion.
66
+ * NOTE: For more granular concurrency, use a "queue" or "pooled" approach.
67
+ *
68
+ * @template T
69
+ * @param {Array<() => Promise<T>>} tasks - An array of functions that return Promises.
70
+ * @param {number} limit - Number of tasks to run in parallel per batch.
71
+ * @returns {Promise<T[]>} A promise that resolves to an array of resolved values.
72
+ */
73
+ export declare function runInBatches<T>(tasks: (() => Promise<T>)[], limit: number): Promise<T[]>;
74
+ /**
75
+ * Wraps a function and ensures it is only called once at a time.
76
+ * Calls made while one is in progress will wait for the same Promise.
77
+ * Optionally, new calls can be dropped while in progress (drop=true).
78
+ *
79
+ * @template TArgs
80
+ * @template TResult
81
+ * @param {(...args: TArgs) => Promise<TResult>} fn - The async function to wrap.
82
+ * @param {boolean} [drop=false] - If true, new calls while one is pending are rejected.
83
+ * @returns {(...args: TArgs) => Promise<TResult>} A wrapped function with singleton behavior.
84
+ */
85
+ export declare function singletonAsync<TArgs extends unknown[], TResult>(fn: (...args: TArgs) => Promise<TResult>, drop?: boolean): (...args: TArgs) => Promise<TResult>;
86
+ /**
87
+ * Resolves a list of async tasks in parallel, returning both resolved and rejected results.
88
+ *
89
+ * @template T
90
+ * @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
91
+ * @returns {Promise<PromiseSettledResult<T>[]>} Results including status and value/reason.
92
+ */
93
+ export declare function settleAll<T>(tasks: (() => Promise<T>)[]): Promise<PromiseSettledResult<T>[]>;
94
+ export interface TaskQueue {
95
+ <T>(taskFn: () => Promise<T>): Promise<T>;
96
+ pause: () => void;
97
+ resume: () => void;
98
+ readonly length: number;
99
+ readonly isPaused: boolean;
100
+ }
101
+ /**
102
+ * A simple task queue that executes async tasks with a concurrency limit.
103
+ * Exposes pause, resume, and queue length getters.
104
+ *
105
+ * @param {number} limit - Maximum number of concurrent tasks.
106
+ * @returns {function & { pause: () => void, resume: () => void, length: number, isPaused: boolean }}
107
+ * Enqueue function plus queue controls.
108
+ */
109
+ export declare function createTaskQueue(limit: number): TaskQueue;
110
+ /**
111
+ * Executes async functions sequentially and collects results.
112
+ * Useful when order matters or tasks depend on each other.
113
+ *
114
+ * @template T
115
+ * @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
116
+ * @returns {Promise<T[]>} Array of resolved values.
117
+ */
118
+ export declare function runInSeries<T>(tasks: (() => Promise<T>)[]): Promise<T[]>;
119
+ //# sourceMappingURL=async.utils.d.ts.map