@andrew_l/toolkit 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.
- package/LICENSE +21 -0
- package/README.md +12 -0
- package/dist/index.cjs +3446 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +3725 -0
- package/dist/index.d.mts +3725 -0
- package/dist/index.d.ts +3725 -0
- package/dist/index.mjs +3267 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +37 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3725 @@
|
|
|
1
|
+
import * as lodash from 'lodash';
|
|
2
|
+
|
|
3
|
+
type ItemType<T> = T extends Array<infer X> ? X : T extends string ? string : Exclude<T, null | undefined>;
|
|
4
|
+
/**
|
|
5
|
+
* Converts a value into an array. This function handles different types of input,
|
|
6
|
+
* converting them to arrays as follows:
|
|
7
|
+
* - If the value is already an array, it returns it as-is.
|
|
8
|
+
* - If the value is a string, it splits the string by commas and trims the elements.
|
|
9
|
+
* - If the value is null or undefined, it returns an empty array.
|
|
10
|
+
* - Otherwise, it wraps the value in an array.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* arrayable(42); // [42]
|
|
14
|
+
* arrayable('a, b, c'); // ['a', 'b', 'c']
|
|
15
|
+
* arrayable([1, 2, 3]); // [1, 2, 3]
|
|
16
|
+
* arrayable(null); // []
|
|
17
|
+
* arrayable(undefined); // []
|
|
18
|
+
*
|
|
19
|
+
* @param value The value to convert into an array. It can be of any type.
|
|
20
|
+
* @returns An array derived from the input value.
|
|
21
|
+
*
|
|
22
|
+
* @group Array
|
|
23
|
+
*/
|
|
24
|
+
declare function arrayable<T>(value: Readonly<T>): ItemType<T>[];
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Calculates the average value from an array of numbers.
|
|
28
|
+
*
|
|
29
|
+
* The function sums up all valid numbers in the array and divides by the count of those valid numbers.
|
|
30
|
+
* If the array is empty or contains no valid numbers, it returns `0`.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* avg([5, 5, 5]); // 5
|
|
34
|
+
* avg([10, 20, 30]); // 20
|
|
35
|
+
* avg([1, 2, 'three', 4]); // 2.33 (ignores non-numeric values)
|
|
36
|
+
* avg([]); // 0
|
|
37
|
+
*
|
|
38
|
+
* @param values An array of numbers (could include invalid values, which will be ignored).
|
|
39
|
+
* @returns The average value of the valid numbers in the array, or `0` if no valid numbers exist.
|
|
40
|
+
*
|
|
41
|
+
* @group Array
|
|
42
|
+
*/
|
|
43
|
+
declare const avg: (values: readonly number[]) => number;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Splits an array into smaller sub-arrays (chunks) of a specified size.
|
|
47
|
+
*
|
|
48
|
+
* If the array can't be evenly divided, the last chunk will contain the remaining elements.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* const data = [1, 2, 3, 4, 5, 6, 7, 8, 9];
|
|
52
|
+
* const chunkSize = 3;
|
|
53
|
+
* const result = chunk(data, chunkSize);
|
|
54
|
+
* console.log(result);
|
|
55
|
+
* // [
|
|
56
|
+
* // [1, 2, 3],
|
|
57
|
+
* // [4, 5, 6],
|
|
58
|
+
* // [7, 8, 9]
|
|
59
|
+
* // ]
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* const data = [1, 2, 3, 4, 5];
|
|
63
|
+
* const chunkSize = 2;
|
|
64
|
+
* const result = chunk(data, chunkSize);
|
|
65
|
+
* console.log(result);
|
|
66
|
+
* // [
|
|
67
|
+
* // [1, 2],
|
|
68
|
+
* // [3, 4],
|
|
69
|
+
* // [5]
|
|
70
|
+
* // ]
|
|
71
|
+
*
|
|
72
|
+
* @param list The array to be split into chunks.
|
|
73
|
+
* @param size The size of each chunk. Defaults to `1` if not specified.
|
|
74
|
+
* @returns An array of arrays (chunks), each containing up to `size` elements from the original array.
|
|
75
|
+
*
|
|
76
|
+
* @group Array
|
|
77
|
+
*/
|
|
78
|
+
declare function chunk<T>(list: readonly T[], size?: number): T[][];
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Collapses a continuous series into a tuple of two elements.
|
|
82
|
+
*
|
|
83
|
+
* Where the first element is the beginning of the series.
|
|
84
|
+
* Where the second element is the end of the series.
|
|
85
|
+
*
|
|
86
|
+
* ⚠️ Tuple may consist only one element if the series not started, like: [1, 3] => [[1], [3]]
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* const numbers = [1, 2, 3, 8, 9, 10, 15];
|
|
90
|
+
*
|
|
91
|
+
* chunkSeries(numbers); // [[1, 3], [8, 10], [15]]
|
|
92
|
+
*
|
|
93
|
+
* @group Array
|
|
94
|
+
*/
|
|
95
|
+
declare function chunkSeries(list: number[], step?: number): number[][];
|
|
96
|
+
|
|
97
|
+
type MaybePropertyKey<T> = T extends object
|
|
98
|
+
? keyof T | PropertyKey
|
|
99
|
+
: PropertyKey;
|
|
100
|
+
|
|
101
|
+
type PropertyKeyLiteralToType<T> = T extends string
|
|
102
|
+
? string
|
|
103
|
+
: T extends number
|
|
104
|
+
? number
|
|
105
|
+
: T extends symbol
|
|
106
|
+
? symbol
|
|
107
|
+
: T;
|
|
108
|
+
|
|
109
|
+
type IsPropertyKey<T, V, L> = T extends object
|
|
110
|
+
? V extends keyof T
|
|
111
|
+
? T[V]
|
|
112
|
+
: L
|
|
113
|
+
: PropertyKeyLiteralToType<L>;
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Maps each element of an array based on a provided key.
|
|
117
|
+
*
|
|
118
|
+
* @example
|
|
119
|
+
* const data = [
|
|
120
|
+
* { id: 1, name: 'group 1' },
|
|
121
|
+
* { id: 2, name: 'group 2' },
|
|
122
|
+
* { id: 1, name: 'group 2' }
|
|
123
|
+
* ];
|
|
124
|
+
*
|
|
125
|
+
* const result = keyBy(data, 'id');
|
|
126
|
+
* console.log(Object.entries(result));
|
|
127
|
+
* // [
|
|
128
|
+
* // [1, [{ id: 1, name: 'group 1' }, { id: 1, name: 'group 2' }],
|
|
129
|
+
* // [2, { id: 2, name: 'group 2' }],
|
|
130
|
+
* // ]
|
|
131
|
+
*
|
|
132
|
+
* @group Array
|
|
133
|
+
*/
|
|
134
|
+
declare function keyBy<T, K extends MaybePropertyKey<T>>(array: readonly T[], keyBy: K, objectMode?: false): Map<IsPropertyKey<T, K, K>, T>;
|
|
135
|
+
declare function keyBy<T, K>(array: readonly T[], keyBy: (item: T) => K, objectMode?: false): Map<K, T>;
|
|
136
|
+
declare function keyBy<T, K extends MaybePropertyKey<T>>(array: readonly T[], keyBy: K, objectMode: true): Record<K, T>;
|
|
137
|
+
declare function keyBy<T, K extends PropertyKey>(array: readonly T[], keyBy: (item: T) => K, objectMode: true): Record<K, T>;
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Sort array by multiple fields
|
|
141
|
+
*
|
|
142
|
+
* @example
|
|
143
|
+
* // Sample data: an array of objects representing users
|
|
144
|
+
* const users = [
|
|
145
|
+
* { name: 'Alice', age: 30, score: 85 },
|
|
146
|
+
* { name: 'Bob', age: 25, score: 90 },
|
|
147
|
+
* { name: 'Charlie', age: 35, score: 90 },
|
|
148
|
+
* { name: 'Dave', age: 30, score: 70 },
|
|
149
|
+
* ];
|
|
150
|
+
*
|
|
151
|
+
* // Sort users first by score in descending order, then by age in ascending order
|
|
152
|
+
* const sortedUsers = orderBy(users, ['score', 'age'], ['desc', 'asc']);
|
|
153
|
+
*
|
|
154
|
+
* // Output the sorted array
|
|
155
|
+
* console.log(sortedUsers);
|
|
156
|
+
*
|
|
157
|
+
* @group Array
|
|
158
|
+
*/
|
|
159
|
+
declare function orderBy<T>(array: readonly T[], fields: (string | ((item: T) => any))[], orders: ('asc' | 'desc')[]): readonly T[];
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Sums the values in an array of numbers, ignoring non-numeric values.
|
|
163
|
+
*
|
|
164
|
+
* This function adds all valid numbers in the array and returns the sum.
|
|
165
|
+
* Non-numeric values (e.g., `null`, `undefined`, `NaN` are ignored in the sum.
|
|
166
|
+
*
|
|
167
|
+
* @example
|
|
168
|
+
* sum([2, 2]); // 4
|
|
169
|
+
* sum([1, 'a', 3, 4]); // 8 (non-numeric 'a' is ignored)
|
|
170
|
+
* sum([5, null, 10]); // 15 (null is ignored)
|
|
171
|
+
* sum([]); // 0 (empty array returns 0)
|
|
172
|
+
*
|
|
173
|
+
* @param values The array of numbers to be summed.
|
|
174
|
+
* @returns The sum of the numbers in the array.
|
|
175
|
+
*
|
|
176
|
+
* @group Array
|
|
177
|
+
*/
|
|
178
|
+
declare const sum: (values: readonly number[]) => number;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Creates an array of unique values from all given arrays.
|
|
182
|
+
*
|
|
183
|
+
* This function takes two arrays, merges them into a single array, and returns a new array
|
|
184
|
+
* containing only the unique values from the merged array.
|
|
185
|
+
*
|
|
186
|
+
* @template T - The type of elements in the array.
|
|
187
|
+
* @param {T[]} arr1 - The first array to merge and filter for unique values.
|
|
188
|
+
* @param {T[]} arr2 - The second array to merge and filter for unique values.
|
|
189
|
+
* @returns {T[]} A new array of unique values.
|
|
190
|
+
*
|
|
191
|
+
* @example
|
|
192
|
+
* const array1 = [1, 2, 3];
|
|
193
|
+
* const array2 = [3, 4, 5];
|
|
194
|
+
* const result = union(array1, array2);
|
|
195
|
+
* // result will be [1, 2, 3, 4, 5]
|
|
196
|
+
*
|
|
197
|
+
* @group Array
|
|
198
|
+
*/
|
|
199
|
+
declare function union<T>(arr1: readonly T[], arr2: readonly T[]): T[];
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Returns a new array with duplicates removed.
|
|
203
|
+
*
|
|
204
|
+
* This function creates a new array that contains only unique values,
|
|
205
|
+
* preserving the order of the original elements.
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* uniq([1, 2, 3, 4, 1, 3]); // [1, 2, 3, 4]
|
|
209
|
+
* uniq([5, 5, 5, 5, 5]); // [5]
|
|
210
|
+
* uniq(['a', 'b', 'a', 'c']); // ['a', 'b', 'c']
|
|
211
|
+
* uniq([]); // [] (returns an empty array for empty input)
|
|
212
|
+
*
|
|
213
|
+
* @param value The array from which duplicates will be removed.
|
|
214
|
+
* @returns A new array containing only the unique values from the input array.
|
|
215
|
+
*
|
|
216
|
+
* @group Array
|
|
217
|
+
*/
|
|
218
|
+
declare function uniq<T extends any[]>(value: T): T;
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Extracts unique elements from an array based on a comparator function or property key.
|
|
222
|
+
*
|
|
223
|
+
* This function allows you to determine uniqueness based on custom criteria by passing
|
|
224
|
+
* a comparator function or a property key. The function will return a new array containing
|
|
225
|
+
* only the first occurrence of elements that are unique according to the specified comparator.
|
|
226
|
+
* If the comparator is a property key, uniqueness will be determined based on the value
|
|
227
|
+
* of that property.
|
|
228
|
+
*
|
|
229
|
+
* @example
|
|
230
|
+
* const users = [
|
|
231
|
+
* { id: 1, role: 'admin' },
|
|
232
|
+
* { id: 2, role: 'admin' },
|
|
233
|
+
* { id: 3, role: 'user' },
|
|
234
|
+
* { id: 4, role: 'user' },
|
|
235
|
+
* ];
|
|
236
|
+
*
|
|
237
|
+
* const uniqRoles = uniqBy(users, (v) => v.role);
|
|
238
|
+
* // [
|
|
239
|
+
* // { id: 1, role: 'admin' },
|
|
240
|
+
* // { id: 3, role: 'user' },
|
|
241
|
+
* // ]
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* const products = [
|
|
245
|
+
* { id: 1, category: 'electronics', name: 'Phone' },
|
|
246
|
+
* { id: 2, category: 'electronics', name: 'Laptop' },
|
|
247
|
+
* { id: 3, category: 'furniture', name: 'Sofa' },
|
|
248
|
+
* ];
|
|
249
|
+
*
|
|
250
|
+
* const uniqCategories = uniqBy(products, 'category');
|
|
251
|
+
* // [
|
|
252
|
+
* // { id: 1, category: 'electronics', name: 'Phone' },
|
|
253
|
+
* // { id: 3, category: 'furniture', name: 'Sofa' },
|
|
254
|
+
* // ]
|
|
255
|
+
*
|
|
256
|
+
* @param array The array to extract unique elements from.
|
|
257
|
+
* @param comparator A function that computes the value to determine uniqueness or a property key.
|
|
258
|
+
* If a string is passed, it is treated as a property key, and uniqueness is
|
|
259
|
+
* determined based on the value of that property.
|
|
260
|
+
* @returns A new array containing only the first occurrence of each unique element based on the comparator.
|
|
261
|
+
*
|
|
262
|
+
* @group Array
|
|
263
|
+
*/
|
|
264
|
+
declare function uniqBy<T>(array: T[], comparator: ((value: T) => any) | PropertyKey): T[];
|
|
265
|
+
|
|
266
|
+
declare function ok(value: unknown, message?: string | Error): asserts value;
|
|
267
|
+
declare function equal<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T;
|
|
268
|
+
declare function object(value: unknown, message?: string | Error): asserts value is object;
|
|
269
|
+
declare function string(value: unknown, message?: string | Error): asserts value is string;
|
|
270
|
+
declare function boolean(value: unknown, message?: string | Error): asserts value is boolean;
|
|
271
|
+
declare function notEmptyString(value: unknown, message?: string | Error): asserts value is string;
|
|
272
|
+
declare function number(value: unknown, message?: string | Error): asserts value is number;
|
|
273
|
+
/**
|
|
274
|
+
* @param {unknown} value
|
|
275
|
+
* @param {string | Error} [message]
|
|
276
|
+
* @return {asserts value is Array}
|
|
277
|
+
*/
|
|
278
|
+
declare function array(value: unknown, message?: string | Error): asserts value is unknown[];
|
|
279
|
+
declare function arrayStrings(value: unknown, message?: string | Error): asserts value is string[];
|
|
280
|
+
declare function arrayNumbers(value: unknown, message?: string | Error): asserts value is number[];
|
|
281
|
+
|
|
282
|
+
declare const assert_array: typeof array;
|
|
283
|
+
declare const assert_arrayNumbers: typeof arrayNumbers;
|
|
284
|
+
declare const assert_arrayStrings: typeof arrayStrings;
|
|
285
|
+
declare const assert_boolean: typeof boolean;
|
|
286
|
+
declare const assert_equal: typeof equal;
|
|
287
|
+
declare const assert_notEmptyString: typeof notEmptyString;
|
|
288
|
+
declare const assert_number: typeof number;
|
|
289
|
+
declare const assert_object: typeof object;
|
|
290
|
+
declare const assert_ok: typeof ok;
|
|
291
|
+
declare const assert_string: typeof string;
|
|
292
|
+
declare namespace assert {
|
|
293
|
+
export { assert_array as array, assert_arrayNumbers as arrayNumbers, assert_arrayStrings as arrayStrings, assert_boolean as boolean, assert_equal as equal, assert_notEmptyString as notEmptyString, assert_number as number, assert_object as object, assert_ok as ok, assert_string as string };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
type Arrayable<T> = T[] | T;
|
|
297
|
+
|
|
298
|
+
type Awaitable<T> = Promise<T> | T;
|
|
299
|
+
|
|
300
|
+
type ArgumentsType<T> = T extends (...args: infer U) => any ? U : never;
|
|
301
|
+
|
|
302
|
+
type FunctionArgs<Args extends any[] = any[], Return = void> = (
|
|
303
|
+
...args: Args
|
|
304
|
+
) => Return;
|
|
305
|
+
|
|
306
|
+
type DeepPartial<T> = T extends object
|
|
307
|
+
? { [P in keyof T]?: DeepPartial<T[P]> }
|
|
308
|
+
: T;
|
|
309
|
+
|
|
310
|
+
type AnyFunction = (...args: any[]) => any;
|
|
311
|
+
|
|
312
|
+
type Data = Record<string, unknown>;
|
|
313
|
+
|
|
314
|
+
type GenericObject = Record<string, any>;
|
|
315
|
+
|
|
316
|
+
type SelectOptions<T = any> = SelectOptionItem<T>[];
|
|
317
|
+
|
|
318
|
+
type OverwriteWith<T1, T2> =
|
|
319
|
+
IsAny<T2> extends true ? T1 : Omit<T1, keyof T2> & T2;
|
|
320
|
+
|
|
321
|
+
type IsAny<T> = boolean extends (T extends never ? true : false)
|
|
322
|
+
? true
|
|
323
|
+
: false;
|
|
324
|
+
|
|
325
|
+
type IfAny<T, Y, N> = 0 extends 1 & T ? Y : N;
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* @example
|
|
329
|
+
* LiteralUnion<'foo' | 'bar', string>
|
|
330
|
+
*
|
|
331
|
+
* @see {@link https://github.com/microsoft/TypeScript/issues/29729}
|
|
332
|
+
*/
|
|
333
|
+
type LiteralUnion<Union, Type> = Union | (Type & Nothing);
|
|
334
|
+
|
|
335
|
+
interface Nothing {}
|
|
336
|
+
|
|
337
|
+
type ValuesOfObject<T> = T[keyof T];
|
|
338
|
+
|
|
339
|
+
type Fn = () => void;
|
|
340
|
+
|
|
341
|
+
type PromisifyFn<T extends AnyFunction> = (
|
|
342
|
+
...args: ArgumentsType<T>
|
|
343
|
+
) => Promise<ReturnType<T>>;
|
|
344
|
+
|
|
345
|
+
type TimeObject = {
|
|
346
|
+
h: number;
|
|
347
|
+
m: number;
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
interface ThemeConfig {
|
|
351
|
+
colors: {
|
|
352
|
+
[x: string]: Record<string, string>;
|
|
353
|
+
};
|
|
354
|
+
variables: {
|
|
355
|
+
[x: string]: Record<string, string | number>;
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
type Prettify<T> = {
|
|
360
|
+
[K in keyof T]: T[K];
|
|
361
|
+
} & {};
|
|
362
|
+
|
|
363
|
+
interface SelectOptionItem<T = any> {
|
|
364
|
+
text: string;
|
|
365
|
+
value: T;
|
|
366
|
+
props?: any;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
interface SelectOptionItem<T = any> {
|
|
370
|
+
text: string;
|
|
371
|
+
value: T;
|
|
372
|
+
props?: any;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
type Primitive =
|
|
376
|
+
| null
|
|
377
|
+
| undefined
|
|
378
|
+
| string
|
|
379
|
+
| number
|
|
380
|
+
| bigint
|
|
381
|
+
| boolean
|
|
382
|
+
| symbol;
|
|
383
|
+
|
|
384
|
+
type ExecResult<T extends Data = Data, K extends Data = Data> =
|
|
385
|
+
| ExecSuccess<T>
|
|
386
|
+
| ExecSkip<K>;
|
|
387
|
+
|
|
388
|
+
type ExecSuccess<T extends Data = Data> = {
|
|
389
|
+
success: true;
|
|
390
|
+
code: string;
|
|
391
|
+
reason?: string;
|
|
392
|
+
} & T;
|
|
393
|
+
|
|
394
|
+
type ExecSkip<T extends Data = Data> = {
|
|
395
|
+
skip: true;
|
|
396
|
+
code: string;
|
|
397
|
+
reason?: string;
|
|
398
|
+
} & T;
|
|
399
|
+
|
|
400
|
+
type ExecResultToSuccess<T> =
|
|
401
|
+
T extends ExecSuccess<infer X> ? ExecSuccess<X> : ExecSuccess;
|
|
402
|
+
|
|
403
|
+
type ExecResultToSkip<T> =
|
|
404
|
+
T extends ExecSkip<infer X> ? ExecSkip<X> : ExecSkip;
|
|
405
|
+
|
|
406
|
+
interface Logger {
|
|
407
|
+
info: (...args: unknown[]) => void;
|
|
408
|
+
warn: (...args: unknown[]) => void;
|
|
409
|
+
error: (...args: unknown[]) => void;
|
|
410
|
+
debug: (...args: unknown[]) => void;
|
|
411
|
+
log: (...args: unknown[]) => void;
|
|
412
|
+
extend: (...args: unknown[]) => void;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
interface ArgToKeyOptions {
|
|
416
|
+
/**
|
|
417
|
+
* Object key generation strategy.
|
|
418
|
+
*
|
|
419
|
+
* When `json` we will use `JSON.stringify` which not quite effective.
|
|
420
|
+
* Also may not hit into cache when object has different key order.
|
|
421
|
+
*
|
|
422
|
+
* When `ref` we will use WeakMap to store object key which more effective but may produce unexpected cache hit.
|
|
423
|
+
*
|
|
424
|
+
* @default `ref`
|
|
425
|
+
*/
|
|
426
|
+
objectStrategy: 'json' | 'ref';
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
interface CreateWithCacheOptions<T extends AnyFunction> extends Partial<ArgToKeyOptions> {
|
|
430
|
+
getBucket: (pointer: WithCachePointer) => WithCacheStorage;
|
|
431
|
+
getPointer: () => WithCachePointer;
|
|
432
|
+
fn: T;
|
|
433
|
+
}
|
|
434
|
+
type WithCachePointer = object | Function | symbol;
|
|
435
|
+
interface WithCacheStorage {
|
|
436
|
+
get(key: unknown): unknown;
|
|
437
|
+
has(key: unknown): boolean;
|
|
438
|
+
delete(key: unknown): void;
|
|
439
|
+
set(key: unknown, value: unknown): void;
|
|
440
|
+
}
|
|
441
|
+
interface WithCache {
|
|
442
|
+
$cache: {
|
|
443
|
+
getBucket: () => WithCacheStorage;
|
|
444
|
+
getPointer: () => WithCachePointer;
|
|
445
|
+
argToKeyOptions: ArgToKeyOptions;
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
type WithCacheResult<T extends AnyFunction> = T & WithCache;
|
|
449
|
+
declare function createWithCache<T extends AnyFunction>({ fn, getPointer, getBucket, objectStrategy, }: CreateWithCacheOptions<T>): WithCacheResult<T>;
|
|
450
|
+
/**
|
|
451
|
+
* Returns true when function is cached
|
|
452
|
+
* @group Cache
|
|
453
|
+
*/
|
|
454
|
+
declare function isWithCache(value: unknown): value is WithCacheResult<AnyFunction>;
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Drop cached result
|
|
458
|
+
*
|
|
459
|
+
* @example
|
|
460
|
+
* const findUser = withCache((id: number) => db.users.findById(id));
|
|
461
|
+
*
|
|
462
|
+
* dropCache(findUser, 100500);
|
|
463
|
+
*
|
|
464
|
+
* @group Cache
|
|
465
|
+
*/
|
|
466
|
+
declare function dropCache(cachePointer: WithCachePointer, ...args: any[]): boolean;
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* A Map-like class with a fixed capacity, where entries are automatically removed
|
|
470
|
+
* when the capacity is exceeded. This allows for efficient caching behavior,
|
|
471
|
+
* ensuring that the map never grows beyond the specified capacity.
|
|
472
|
+
*
|
|
473
|
+
* When the map reaches its capacity, the oldest entries (in insertion order)
|
|
474
|
+
* are removed to make room for new ones.
|
|
475
|
+
*
|
|
476
|
+
* @example
|
|
477
|
+
* const cache = new FixedMap<string, number>(3);
|
|
478
|
+
* cache.set('a', 1);
|
|
479
|
+
* cache.set('b', 2);
|
|
480
|
+
* cache.set('c', 3);
|
|
481
|
+
* cache.set('d', 4); // 'a' will be evicted, as it's the oldest entry
|
|
482
|
+
*
|
|
483
|
+
* console.log(cache.get('a')); // undefined
|
|
484
|
+
* console.log(cache.get('b')); // 2
|
|
485
|
+
*
|
|
486
|
+
* @group Cache
|
|
487
|
+
*/
|
|
488
|
+
declare class FixedMap<K = any, V = any> extends Map<K, V> {
|
|
489
|
+
private _capacity;
|
|
490
|
+
private _tail;
|
|
491
|
+
constructor(_capacity: number);
|
|
492
|
+
set(key: K, value: V): this;
|
|
493
|
+
delete(key: K): boolean;
|
|
494
|
+
clear(): void;
|
|
495
|
+
get capacity(): number;
|
|
496
|
+
set capacity(value: number);
|
|
497
|
+
private _drain;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* A `WeakMap`-like class with a fixed capacity. Entries are automatically removed
|
|
502
|
+
* when the map exceeds the specified capacity. Unlike a regular `WeakMap`, the
|
|
503
|
+
* entries are limited to a defined size, and the oldest entries are evicted when
|
|
504
|
+
* new ones are added after the capacity is reached.
|
|
505
|
+
*
|
|
506
|
+
* This class behaves similarly to a `WeakMap`, but with the additional constraint
|
|
507
|
+
* of a fixed size. It automatically removes the least recently added key-value
|
|
508
|
+
* pairs when the map grows beyond the specified capacity.
|
|
509
|
+
*
|
|
510
|
+
* @example
|
|
511
|
+
* const cache = new FixedWeakMap<object, number>(3);
|
|
512
|
+
* const obj1 = { id: 1 };
|
|
513
|
+
* const obj2 = { id: 2 };
|
|
514
|
+
* const obj3 = { id: 3 };
|
|
515
|
+
*
|
|
516
|
+
* cache.set(obj1, 1);
|
|
517
|
+
* cache.set(obj2, 2);
|
|
518
|
+
* cache.set(obj3, 3);
|
|
519
|
+
*
|
|
520
|
+
* const obj4 = { id: 4 };
|
|
521
|
+
* cache.set(obj4, 4); // obj1 will be evicted as it's the oldest
|
|
522
|
+
*
|
|
523
|
+
* console.log(cache.get(obj1)); // undefined
|
|
524
|
+
* console.log(cache.get(obj2)); // 2
|
|
525
|
+
* console.log(cache.get(obj4)); // 4
|
|
526
|
+
*
|
|
527
|
+
* @group Cache
|
|
528
|
+
*/
|
|
529
|
+
declare class FixedWeakMap<K extends WeakKey = WeakKey, V = any> extends WeakMap<K, V> {
|
|
530
|
+
private _capacity;
|
|
531
|
+
private _tail;
|
|
532
|
+
constructor(_capacity: number);
|
|
533
|
+
set(key: K, value: V): this;
|
|
534
|
+
delete(key: K): boolean;
|
|
535
|
+
clear(): void;
|
|
536
|
+
get size(): number;
|
|
537
|
+
get capacity(): number;
|
|
538
|
+
set capacity(value: number);
|
|
539
|
+
private _drain;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Check if function has cached result
|
|
544
|
+
*
|
|
545
|
+
* @example
|
|
546
|
+
* const findUser = withCache((id: number) => db.users.findById(id));
|
|
547
|
+
*
|
|
548
|
+
* const user = findUser(100500);
|
|
549
|
+
*
|
|
550
|
+
* isCached(findUser, 100500); // true
|
|
551
|
+
*
|
|
552
|
+
* @group Cache
|
|
553
|
+
*/
|
|
554
|
+
declare function isCached<T extends AnyFunction>(fn: AnyFunction, ...args: Parameters<T>): boolean;
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* A simple implementation of a Least Recently Used (LRU) cache. This cache stores
|
|
558
|
+
* key-value pairs and ensures that the most recently accessed items are kept
|
|
559
|
+
* in the cache, while the least recently used items are evicted when the cache
|
|
560
|
+
* reaches its capacity.
|
|
561
|
+
*
|
|
562
|
+
* The cache is implemented as a doubly linked list where the head represents
|
|
563
|
+
* the most recently accessed item, and the tail represents the least recently
|
|
564
|
+
* accessed item. When the cache is full, the least recently used item (tail)
|
|
565
|
+
* is removed to make space for new items.
|
|
566
|
+
*
|
|
567
|
+
* @group Cache
|
|
568
|
+
*/
|
|
569
|
+
declare class LruCache<TKey = any, TValue = any> {
|
|
570
|
+
private capacity;
|
|
571
|
+
private items;
|
|
572
|
+
private forward;
|
|
573
|
+
private backward;
|
|
574
|
+
private K;
|
|
575
|
+
private V;
|
|
576
|
+
size: number;
|
|
577
|
+
private head;
|
|
578
|
+
private tail;
|
|
579
|
+
constructor(capacity: number);
|
|
580
|
+
/**
|
|
581
|
+
* Method used to clear the structure.
|
|
582
|
+
*/
|
|
583
|
+
clear(): void;
|
|
584
|
+
set(key: TKey, value: TValue): this;
|
|
585
|
+
has(key: TKey): boolean;
|
|
586
|
+
delete(key: TKey): void;
|
|
587
|
+
get(key: TKey): TValue | undefined;
|
|
588
|
+
/**
|
|
589
|
+
* Method used to get the value attached to the given key. Does not modify
|
|
590
|
+
* the ordering of the underlying linked list.
|
|
591
|
+
*/
|
|
592
|
+
peek(key: TKey): TValue | undefined;
|
|
593
|
+
/**
|
|
594
|
+
* Method used to create an iterator over the cache's keys from most
|
|
595
|
+
* recently used to least recently used.
|
|
596
|
+
*/
|
|
597
|
+
keys(): IterableIterator<TKey>;
|
|
598
|
+
/**
|
|
599
|
+
* Method used to create an iterator over the cache's values from most
|
|
600
|
+
* recently used to least recently used.
|
|
601
|
+
*
|
|
602
|
+
*/
|
|
603
|
+
values(): IterableIterator<TValue>;
|
|
604
|
+
/**
|
|
605
|
+
* Method used to create an iterator over the cache's entries from most
|
|
606
|
+
* recently used to least recently used.
|
|
607
|
+
*
|
|
608
|
+
* @return {IterableIterator<[TKey, TValue | undefined]>}
|
|
609
|
+
*/
|
|
610
|
+
entries(): {
|
|
611
|
+
[Symbol.iterator](): any;
|
|
612
|
+
next(): {
|
|
613
|
+
done: boolean;
|
|
614
|
+
value: undefined;
|
|
615
|
+
} | {
|
|
616
|
+
done: boolean;
|
|
617
|
+
value: (TKey | TValue | undefined)[];
|
|
618
|
+
};
|
|
619
|
+
};
|
|
620
|
+
/**
|
|
621
|
+
* Method used to splay a value on top.
|
|
622
|
+
*
|
|
623
|
+
* @param {number} pointer - Pointer of the value to splay on top.
|
|
624
|
+
*/
|
|
625
|
+
splayOnTop(pointer: number): this;
|
|
626
|
+
[Symbol.iterator](): {
|
|
627
|
+
[Symbol.iterator](): any;
|
|
628
|
+
next(): {
|
|
629
|
+
done: boolean;
|
|
630
|
+
value: undefined;
|
|
631
|
+
} | {
|
|
632
|
+
done: boolean;
|
|
633
|
+
value: (TKey | TValue | undefined)[];
|
|
634
|
+
};
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
interface TimeBucketOptions {
|
|
639
|
+
/**
|
|
640
|
+
* The size of each time bucket in milliseconds. This is the interval at which
|
|
641
|
+
* the records in the bucket will expire and be dropped.
|
|
642
|
+
*/
|
|
643
|
+
sizeMs: number;
|
|
644
|
+
/**
|
|
645
|
+
* The maximum number of entries the bucket can hold. Once the capacity is
|
|
646
|
+
* reached, the least recently used entry will be removed.
|
|
647
|
+
* @default Infinity
|
|
648
|
+
*/
|
|
649
|
+
capacity?: number;
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* A time-based bucket that holds records for a specific interval defined by `sizeMs`.
|
|
653
|
+
* The records in the bucket will be dropped once the interval elapses, based on the
|
|
654
|
+
* current time. The `TimeBucket` is designed to avoid using timers to track expirations.
|
|
655
|
+
*
|
|
656
|
+
* It can be used to store data that expires over fixed time intervals (e.g., caching,
|
|
657
|
+
* throttling).
|
|
658
|
+
*
|
|
659
|
+
* @example
|
|
660
|
+
* const bucket = new TimeBucket({ sizeMs: 1000, capacity: 10 });
|
|
661
|
+
* bucket.set('key1', 'value1');
|
|
662
|
+
* console.log(bucket.get('key1')); // 'value1'
|
|
663
|
+
*
|
|
664
|
+
* // After 1 second, the bucket will drop the expired records.
|
|
665
|
+
*
|
|
666
|
+
* @group Cache
|
|
667
|
+
*/
|
|
668
|
+
declare class TimeBucket<K = any, V = any> {
|
|
669
|
+
private _pointer;
|
|
670
|
+
private _sizeMs;
|
|
671
|
+
private _bucket;
|
|
672
|
+
constructor({ capacity, sizeMs }: TimeBucketOptions);
|
|
673
|
+
get capacity(): number;
|
|
674
|
+
get sizeMs(): number;
|
|
675
|
+
set sizeMs(value: number);
|
|
676
|
+
get size(): number;
|
|
677
|
+
set(key: K, value: V): this;
|
|
678
|
+
get(key: K): any | undefined;
|
|
679
|
+
has(key: K): boolean;
|
|
680
|
+
delete(key: K): boolean;
|
|
681
|
+
clear(): void;
|
|
682
|
+
keys(): IterableIterator<K>;
|
|
683
|
+
values(): IterableIterator<V>;
|
|
684
|
+
entries(): IterableIterator<[K, V]>;
|
|
685
|
+
forEach(callbackfn: (value: V, key: K, map: TimeBucket<K, V>) => void, thisArg?: any): void;
|
|
686
|
+
private _drainBucket;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
interface WithCacheOptions extends Partial<ArgToKeyOptions> {
|
|
690
|
+
/**
|
|
691
|
+
* Custom cache pointer
|
|
692
|
+
*/
|
|
693
|
+
cachePointer?: WithCachePointer;
|
|
694
|
+
}
|
|
695
|
+
declare const cache: WeakMap<WithCachePointer, Map<string, any>>;
|
|
696
|
+
/**
|
|
697
|
+
* Wrap a function to cache results by arguments
|
|
698
|
+
*
|
|
699
|
+
* @example
|
|
700
|
+
* const sum = withCache((a, b) => {
|
|
701
|
+
* console.log('calc?');
|
|
702
|
+
* return a + b;
|
|
703
|
+
* });
|
|
704
|
+
*
|
|
705
|
+
* sum(1, 2); // calc?
|
|
706
|
+
* sum(1, 2);
|
|
707
|
+
* sum(1, 3) // calc?
|
|
708
|
+
*
|
|
709
|
+
* @group Cache
|
|
710
|
+
*/
|
|
711
|
+
declare function withCache<T extends AnyFunction>(fn: T): WithCacheResult<T>;
|
|
712
|
+
declare function withCache<T extends AnyFunction>(options: WithCacheOptions, fn: T): WithCacheResult<T>;
|
|
713
|
+
|
|
714
|
+
interface WithCacheBucketOptions extends Partial<ArgToKeyOptions> {
|
|
715
|
+
/**
|
|
716
|
+
* Define cached records drops interval.
|
|
717
|
+
*/
|
|
718
|
+
sizeMs: number;
|
|
719
|
+
/**
|
|
720
|
+
* Capacity of cached records
|
|
721
|
+
*/
|
|
722
|
+
capacity?: number;
|
|
723
|
+
/**
|
|
724
|
+
* Custom cache pointer
|
|
725
|
+
*/
|
|
726
|
+
cachePointer?: WithCachePointer;
|
|
727
|
+
}
|
|
728
|
+
declare const cacheBucket: WeakMap<WithCachePointer, TimeBucket<string, any>>;
|
|
729
|
+
/**
|
|
730
|
+
* Wrap a function to cache results by arguments
|
|
731
|
+
*
|
|
732
|
+
* But with time and capacity limitation
|
|
733
|
+
*
|
|
734
|
+
* @example
|
|
735
|
+
* const sum = withCacheBucket({ capacity: 1, sizeMs: 1000000 }, (a, b) => {
|
|
736
|
+
* console.log('calc?');
|
|
737
|
+
* return a + b;
|
|
738
|
+
* });
|
|
739
|
+
*
|
|
740
|
+
* sum(1, 2); // calc?
|
|
741
|
+
* sum(1, 2);
|
|
742
|
+
* sum(1, 3) // calc?
|
|
743
|
+
* sum(1, 3)
|
|
744
|
+
* sum(1, 2); // calc?
|
|
745
|
+
*
|
|
746
|
+
* @group Cache
|
|
747
|
+
*/
|
|
748
|
+
declare function withCacheBucket<T extends AnyFunction>({ capacity, sizeMs, cachePointer, ...options }: WithCacheBucketOptions, fn: T): WithCacheResult<T>;
|
|
749
|
+
|
|
750
|
+
interface WithCacheBucketBatchOptions<T extends object, K extends keyof T> {
|
|
751
|
+
/**
|
|
752
|
+
* Define cached records drops interval.
|
|
753
|
+
*/
|
|
754
|
+
sizeMs: number;
|
|
755
|
+
/**
|
|
756
|
+
* Cache record by object key.
|
|
757
|
+
*/
|
|
758
|
+
key: K;
|
|
759
|
+
/**
|
|
760
|
+
* Amount of items which will handled by resolver function.
|
|
761
|
+
*/
|
|
762
|
+
batchSize?: number;
|
|
763
|
+
/**
|
|
764
|
+
* Capacity of cached records
|
|
765
|
+
*/
|
|
766
|
+
capacity?: number;
|
|
767
|
+
/**
|
|
768
|
+
* Custom cache pointer
|
|
769
|
+
*/
|
|
770
|
+
cachePointer?: WithCachePointer;
|
|
771
|
+
/**
|
|
772
|
+
* Should we retry resolving for provided item key when previously we got empty result.
|
|
773
|
+
*/
|
|
774
|
+
retryEmpty?: boolean;
|
|
775
|
+
/**
|
|
776
|
+
* Resolving item function
|
|
777
|
+
*/
|
|
778
|
+
resolver?: (values: T[K][]) => Promise<T[]>;
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* In this way we will cache item of resulted array by `key`.
|
|
782
|
+
*
|
|
783
|
+
* Useful when we need for example fetch batch of users by ids but took already cached results if it available.
|
|
784
|
+
*
|
|
785
|
+
* @example TODO
|
|
786
|
+
*
|
|
787
|
+
* @beta
|
|
788
|
+
*
|
|
789
|
+
* @group Cache
|
|
790
|
+
*/
|
|
791
|
+
declare function withCacheBucketBatch<T extends object, K extends keyof T>({ capacity, sizeMs, key, batchSize, cachePointer, retryEmpty, }: WithCacheBucketBatchOptions<T, K>, resolver: (values: T[K][]) => Promise<T[]>): WithCacheResult<(values: T[K][]) => Promise<Map<string, Readonly<T>>>>;
|
|
792
|
+
|
|
793
|
+
interface WithCacheFixedOptions extends Partial<ArgToKeyOptions> {
|
|
794
|
+
/**
|
|
795
|
+
* Capacity of cached records
|
|
796
|
+
*/
|
|
797
|
+
capacity: number;
|
|
798
|
+
/**
|
|
799
|
+
* Custom cache pointer
|
|
800
|
+
*/
|
|
801
|
+
cachePointer?: WithCachePointer;
|
|
802
|
+
}
|
|
803
|
+
declare const cacheFixed: WeakMap<WithCachePointer, FixedMap<string, any>>;
|
|
804
|
+
/**
|
|
805
|
+
* Wrap a function to cache results by arguments
|
|
806
|
+
*
|
|
807
|
+
* But with capacity limitation
|
|
808
|
+
*
|
|
809
|
+
* @example
|
|
810
|
+
* const sum = withCacheFixed({ capacity: 1 }, (a, b) => {
|
|
811
|
+
* console.log('calc?');
|
|
812
|
+
* return a + b;
|
|
813
|
+
* });
|
|
814
|
+
*
|
|
815
|
+
* sum(1, 2); // calc?
|
|
816
|
+
* sum(1, 2);
|
|
817
|
+
* sum(1, 3) // calc?
|
|
818
|
+
* sum(1, 3)
|
|
819
|
+
* sum(1, 2); // calc?
|
|
820
|
+
*
|
|
821
|
+
* @group Cache
|
|
822
|
+
*/
|
|
823
|
+
declare function withCacheFixed<T extends AnyFunction>({ capacity, cachePointer, ...options }: WithCacheFixedOptions, fn: T): WithCacheResult<T>;
|
|
824
|
+
|
|
825
|
+
interface WithCacheLruOptions extends Partial<ArgToKeyOptions> {
|
|
826
|
+
capacity: number;
|
|
827
|
+
cachePointer?: WithCachePointer;
|
|
828
|
+
}
|
|
829
|
+
declare const cacheLRU: WeakMap<WithCachePointer, LruCache<string, any>>;
|
|
830
|
+
/**
|
|
831
|
+
* Wrap a function to cache results by arguments
|
|
832
|
+
*
|
|
833
|
+
* But with LRU
|
|
834
|
+
*
|
|
835
|
+
* @example
|
|
836
|
+
* const sum = withCacheLRU({ capacity: 100 }, (a, b) => {
|
|
837
|
+
* console.log('calc?');
|
|
838
|
+
* return a + b;
|
|
839
|
+
* });
|
|
840
|
+
*
|
|
841
|
+
* sum(1, 2); // calc?
|
|
842
|
+
* sum(1, 2);
|
|
843
|
+
*
|
|
844
|
+
* @group Cache
|
|
845
|
+
*/
|
|
846
|
+
declare function withCacheLRU<T extends AnyFunction>({ capacity, cachePointer, ...options }: WithCacheLruOptions, fn: T): WithCacheResult<T>;
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* Make deep cloning of function result before returning.
|
|
850
|
+
*
|
|
851
|
+
* @example
|
|
852
|
+
* const findUser = withDeepClone(
|
|
853
|
+
* withCache((id: number) => {
|
|
854
|
+
* return { id, name: 'Andrew' };
|
|
855
|
+
* })
|
|
856
|
+
* );
|
|
857
|
+
*
|
|
858
|
+
* const user1 = findUser(100500);
|
|
859
|
+
* const user2 = findUser(100500);
|
|
860
|
+
* user1.name = 'ABC';
|
|
861
|
+
*
|
|
862
|
+
* console.log(user1.name); // ABC
|
|
863
|
+
* console.log(user2.name); // Andrew
|
|
864
|
+
*
|
|
865
|
+
* @group Cache
|
|
866
|
+
*/
|
|
867
|
+
declare function withDeepClone<T extends AnyFunction>(fn: T): T;
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* @example TODO
|
|
871
|
+
* @group Cache
|
|
872
|
+
* @beta
|
|
873
|
+
*/
|
|
874
|
+
declare function withPointerCache<T>(pointer: object, dependencies: string[], fn: () => T): T;
|
|
875
|
+
|
|
876
|
+
/**
|
|
877
|
+
* Capture stack trace till the function and returns as a `string`
|
|
878
|
+
*
|
|
879
|
+
* @example
|
|
880
|
+
*
|
|
881
|
+
* function main() {
|
|
882
|
+
* const userId = getUserId();
|
|
883
|
+
* }
|
|
884
|
+
*
|
|
885
|
+
* function getUserId() {
|
|
886
|
+
* const stackTrace = captureStackTrace(doCoolStuff);
|
|
887
|
+
* console.warn('Please, use getAccountId instead.', stackTrace);
|
|
888
|
+
* }
|
|
889
|
+
*
|
|
890
|
+
* @group Errors
|
|
891
|
+
*/
|
|
892
|
+
declare function captureStackTrace(till: AnyFunction): string;
|
|
893
|
+
|
|
894
|
+
type ToCatchResult<T> = T extends Promise<any> ? Promise<CatchSuccessResult<Awaited<T>> | CatchErrorResult> : CatchSuccessResult<T> | CatchErrorResult;
|
|
895
|
+
type CatchErrorResult = [Error, undefined];
|
|
896
|
+
type CatchSuccessResult<T> = [undefined, T];
|
|
897
|
+
/**
|
|
898
|
+
* You're tired to write `try... catch`, and so are we.
|
|
899
|
+
*
|
|
900
|
+
* Also supports `async/await`
|
|
901
|
+
*
|
|
902
|
+
* @example
|
|
903
|
+
* const [err, result] = catchError(() => {
|
|
904
|
+
* // danger code
|
|
905
|
+
* });
|
|
906
|
+
*
|
|
907
|
+
* @group Errors
|
|
908
|
+
*/
|
|
909
|
+
declare function catchError<T>(fn: () => T): ToCatchResult<T>;
|
|
910
|
+
|
|
911
|
+
declare namespace Color {
|
|
912
|
+
/**
|
|
913
|
+
* From 0 to 1
|
|
914
|
+
*/
|
|
915
|
+
type Alpha = number;
|
|
916
|
+
type HSLA = {
|
|
917
|
+
h: number;
|
|
918
|
+
s: number;
|
|
919
|
+
l: number;
|
|
920
|
+
a: Alpha;
|
|
921
|
+
};
|
|
922
|
+
type RGBA = {
|
|
923
|
+
r: number;
|
|
924
|
+
g: number;
|
|
925
|
+
b: number;
|
|
926
|
+
a: Alpha;
|
|
927
|
+
};
|
|
928
|
+
type HEX = string;
|
|
929
|
+
/**
|
|
930
|
+
* Unified color representation in [red, green, blue, alpha]
|
|
931
|
+
*/
|
|
932
|
+
type ColorChannels = [number, number, number, number];
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
declare function parseHEX(value: unknown): Color.ColorChannels | null;
|
|
936
|
+
|
|
937
|
+
/**
|
|
938
|
+
* Parse a string as a hsl color
|
|
939
|
+
*/
|
|
940
|
+
declare function parseHSL(value: string): Color.HSLA | null;
|
|
941
|
+
|
|
942
|
+
declare function parseRGB(value: unknown): Color.RGBA | null;
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* Check if provided value represents color channels
|
|
946
|
+
* @group Colors
|
|
947
|
+
*/
|
|
948
|
+
declare function isColorChannels(value: unknown): value is Color.ColorChannels;
|
|
949
|
+
|
|
950
|
+
/**
|
|
951
|
+
* Returns css valid color with adjusted alpha channel
|
|
952
|
+
*
|
|
953
|
+
* @example
|
|
954
|
+
* alpha('rgba(0, 0, 0, 0.87)', 1); // 'rgba(0, 0, 0, 1)'
|
|
955
|
+
*
|
|
956
|
+
* @group Colors
|
|
957
|
+
*/
|
|
958
|
+
declare function alpha(color: string | Color.ColorChannels, newAlpha: number): string;
|
|
959
|
+
|
|
960
|
+
/**
|
|
961
|
+
* Just mixing of two colors
|
|
962
|
+
*
|
|
963
|
+
* @example
|
|
964
|
+
* const colorA = 'rgb(50, 100, 100)';
|
|
965
|
+
* const colorB = 'rgb(150, 0, 0)';
|
|
966
|
+
*
|
|
967
|
+
* // [100, 50, 50, 1]
|
|
968
|
+
* blendColors(colorA, colorB, 0.5);
|
|
969
|
+
*
|
|
970
|
+
* @group Colors
|
|
971
|
+
*/
|
|
972
|
+
declare function blendColors(color1: Color.ColorChannels | string, color2: Color.ColorChannels | string, factor: number): Color.ColorChannels;
|
|
973
|
+
|
|
974
|
+
/**
|
|
975
|
+
* Build css valid color from color channels
|
|
976
|
+
*
|
|
977
|
+
* @example
|
|
978
|
+
* const channels = [255, 255, 255, 0.5];
|
|
979
|
+
*
|
|
980
|
+
* buildCssColor(channels); // 'rgba(255, 255, 255, 0.5)'
|
|
981
|
+
*
|
|
982
|
+
* // with applied opacity factor
|
|
983
|
+
* buildCssColor(channels, 0.1); // 'rgba(255, 255, 255, 0.05)'
|
|
984
|
+
*
|
|
985
|
+
* @group Colors
|
|
986
|
+
*/
|
|
987
|
+
declare function buildCssColor([r, g, b, a]: Color.ColorChannels, opacity?: number): string;
|
|
988
|
+
|
|
989
|
+
/**
|
|
990
|
+
* Converts color channels into hex
|
|
991
|
+
*
|
|
992
|
+
* @example
|
|
993
|
+
* const channels = [255, 255, 255, 1];
|
|
994
|
+
*
|
|
995
|
+
* // with alpha channel
|
|
996
|
+
* channelsToHex(channels); // '#FFFFFFFF'
|
|
997
|
+
*
|
|
998
|
+
* // without alpha channel
|
|
999
|
+
* channelsToHex(channels, false); // '#FFFFFF'
|
|
1000
|
+
* @group Colors
|
|
1001
|
+
*/
|
|
1002
|
+
declare function channelsToHex(channels: Color.ColorChannels, withAlpha?: boolean): string;
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* Converts color channels into HSL
|
|
1006
|
+
* @group Colors
|
|
1007
|
+
*/
|
|
1008
|
+
declare function channelsToHSL([r, g, b, a]: Color.ColorChannels): Color.HSLA;
|
|
1009
|
+
|
|
1010
|
+
/**
|
|
1011
|
+
* Converts color channels into RGB
|
|
1012
|
+
* @group Colors
|
|
1013
|
+
*/
|
|
1014
|
+
declare function channelsToRGB([r, g, b, a]: Color.ColorChannels): Color.RGBA;
|
|
1015
|
+
|
|
1016
|
+
/**
|
|
1017
|
+
* Parse css color and returns color channels
|
|
1018
|
+
* @group Colors
|
|
1019
|
+
*/
|
|
1020
|
+
declare function colorToChannels(color: string | Color.ColorChannels): Color.ColorChannels;
|
|
1021
|
+
|
|
1022
|
+
/**
|
|
1023
|
+
* Calculate WCAG 2.0 contrast ratio of two luminance
|
|
1024
|
+
*
|
|
1025
|
+
* @example
|
|
1026
|
+
* const l1 = luminance([255, 255, 255, 1]);
|
|
1027
|
+
* const l2 = luminance([0, 0, 0, 1]);
|
|
1028
|
+
*
|
|
1029
|
+
* contrastRatio(l1, l2); // 21
|
|
1030
|
+
*
|
|
1031
|
+
* @group Colors
|
|
1032
|
+
*/
|
|
1033
|
+
declare function contrastRatio(l1: number, l2: number): number;
|
|
1034
|
+
|
|
1035
|
+
/**
|
|
1036
|
+
* Create a getter of css variable for container
|
|
1037
|
+
* @group Colors
|
|
1038
|
+
*/
|
|
1039
|
+
declare function cssVariable(container: HTMLElement): (name: string) => string;
|
|
1040
|
+
|
|
1041
|
+
/**
|
|
1042
|
+
* Parsing hex string as color channels
|
|
1043
|
+
*
|
|
1044
|
+
* @example
|
|
1045
|
+
* hexToChannels('#FFFFFF'); // [255, 255, 255, 1]
|
|
1046
|
+
* hexToChannels('#FFF'); // [255, 255, 255, 1]
|
|
1047
|
+
*
|
|
1048
|
+
* @group Colors
|
|
1049
|
+
*/
|
|
1050
|
+
declare function hexToChannels(hexWithAlpha: string): Color.ColorChannels;
|
|
1051
|
+
|
|
1052
|
+
/**
|
|
1053
|
+
* Parsing HSL string as color channels
|
|
1054
|
+
*
|
|
1055
|
+
* @example
|
|
1056
|
+
* // [128, 51, 204, 0.15]
|
|
1057
|
+
* hslToChannels('hsl(270 60% 50% / 15%)');
|
|
1058
|
+
*
|
|
1059
|
+
* @group Colors
|
|
1060
|
+
*/
|
|
1061
|
+
declare function hslToChannels(value: string): Color.ColorChannels;
|
|
1062
|
+
|
|
1063
|
+
/**
|
|
1064
|
+
* Linear color interpolating
|
|
1065
|
+
*
|
|
1066
|
+
* @example
|
|
1067
|
+
* // 'rgba(50, 50, 50, 1)'
|
|
1068
|
+
* interpolateColor(
|
|
1069
|
+
* 'rgb(0, 0, 0)',
|
|
1070
|
+
* 'rgb(100, 100, 100)',
|
|
1071
|
+
* 0.5
|
|
1072
|
+
* );
|
|
1073
|
+
*
|
|
1074
|
+
* @group Colors
|
|
1075
|
+
*/
|
|
1076
|
+
declare function interpolateColor(color1: string | Color.ColorChannels, color2: string | Color.ColorChannels, factor: number): Color.ColorChannels;
|
|
1077
|
+
|
|
1078
|
+
/**
|
|
1079
|
+
* Calculate luminance of color
|
|
1080
|
+
*
|
|
1081
|
+
* @example
|
|
1082
|
+
* luminance([255, 255, 255, 1]); // 1
|
|
1083
|
+
* luminance([0, 0, 0, 1]); // 0
|
|
1084
|
+
*
|
|
1085
|
+
* @group Colors
|
|
1086
|
+
*/
|
|
1087
|
+
declare function luminance([r, g, b]: Color.ColorChannels): number;
|
|
1088
|
+
|
|
1089
|
+
/**
|
|
1090
|
+
* Parse alpha channel value and normalize it from 0 to 1
|
|
1091
|
+
*
|
|
1092
|
+
* @param value Value to be parsed
|
|
1093
|
+
* @param fallback Value which will be used as fallback when failed to parse
|
|
1094
|
+
*
|
|
1095
|
+
* @example
|
|
1096
|
+
* parseAlpha('0.1'); // 0.1
|
|
1097
|
+
* parseAlpha('10%'); // 0.1
|
|
1098
|
+
* parseAlpha(0.1); // 0.1
|
|
1099
|
+
*
|
|
1100
|
+
* @group Colors
|
|
1101
|
+
*/
|
|
1102
|
+
declare function parseAlpha(value: unknown, fallback?: number): number;
|
|
1103
|
+
|
|
1104
|
+
/**
|
|
1105
|
+
* Parsing rgb() string as color channels
|
|
1106
|
+
*
|
|
1107
|
+
* @example
|
|
1108
|
+
* // [255, 0, 0, 0.2]
|
|
1109
|
+
* rgbToChannels('rgba(100% 0% 0% / 20%)');
|
|
1110
|
+
*
|
|
1111
|
+
* @group Colors
|
|
1112
|
+
*/
|
|
1113
|
+
declare function rgbToChannels(value: string): Color.ColorChannels;
|
|
1114
|
+
|
|
1115
|
+
/**
|
|
1116
|
+
* Returns a color text color that should be on background to keep good contrast
|
|
1117
|
+
*
|
|
1118
|
+
* @example
|
|
1119
|
+
* const bgColor = 'rgb(255, 255, 255)';
|
|
1120
|
+
* const tint = 1;
|
|
1121
|
+
*
|
|
1122
|
+
* // 'rgba(0, 0, 0, 1)'
|
|
1123
|
+
* const textColor = tintedTextColor(bgColor, tint);
|
|
1124
|
+
*
|
|
1125
|
+
* @group Colors
|
|
1126
|
+
*/
|
|
1127
|
+
declare function tintedTextColor(background: string | Color.ColorChannels, tintPercentage?: number): Color.ColorChannels;
|
|
1128
|
+
|
|
1129
|
+
type ColorChannels = Color.ColorChannels;
|
|
1130
|
+
/**
|
|
1131
|
+
* General color parser api
|
|
1132
|
+
* @group Colors
|
|
1133
|
+
*/
|
|
1134
|
+
declare const ColorParser: {
|
|
1135
|
+
HSL: typeof parseHSL;
|
|
1136
|
+
RGB: typeof parseRGB;
|
|
1137
|
+
HEX: typeof parseHEX;
|
|
1138
|
+
};
|
|
1139
|
+
|
|
1140
|
+
/**
|
|
1141
|
+
* Calculate crc32 hash from string
|
|
1142
|
+
* @group Crypto
|
|
1143
|
+
*/
|
|
1144
|
+
declare function crc32(str: string, seed?: number): number;
|
|
1145
|
+
|
|
1146
|
+
type Dict<T> = {
|
|
1147
|
+
[key: string]: T | undefined;
|
|
1148
|
+
};
|
|
1149
|
+
type ListTypeName = 'bool' | 'int' | 'decimal' | 'string';
|
|
1150
|
+
type ListTypeNameToType<T extends ListTypeName> = T extends 'bool' ? boolean : T extends 'int' ? number : T extends 'decimal' ? number : T extends 'string' ? string : never;
|
|
1151
|
+
/**
|
|
1152
|
+
* Environment variable parser
|
|
1153
|
+
*
|
|
1154
|
+
* @group Environment
|
|
1155
|
+
*/
|
|
1156
|
+
interface EnvParser {
|
|
1157
|
+
/**
|
|
1158
|
+
* NODE_ENV is `development`
|
|
1159
|
+
*/
|
|
1160
|
+
isDevelopment: boolean;
|
|
1161
|
+
/**
|
|
1162
|
+
* NODE_ENV is `production`
|
|
1163
|
+
*/
|
|
1164
|
+
isProduction: boolean;
|
|
1165
|
+
/**
|
|
1166
|
+
* NODE_ENV is `stage`
|
|
1167
|
+
*/
|
|
1168
|
+
isStage: boolean;
|
|
1169
|
+
/**
|
|
1170
|
+
* Returns `true` when environment key has set to `"true"`
|
|
1171
|
+
*
|
|
1172
|
+
* Returns `defaultValue` when key is not defined
|
|
1173
|
+
*/
|
|
1174
|
+
bool(key: string, defaultValue?: boolean): boolean;
|
|
1175
|
+
/**
|
|
1176
|
+
* Returns `number` when environment key has correct number value.
|
|
1177
|
+
*
|
|
1178
|
+
* Returns `defaultValue` when environment key is not defined or has invalid number value
|
|
1179
|
+
*/
|
|
1180
|
+
int(key: string, defaultValue?: number): number;
|
|
1181
|
+
/**
|
|
1182
|
+
* Returns `number` when environment key has correct number value.
|
|
1183
|
+
*
|
|
1184
|
+
* Returns `defaultValue` when environment key is not defined or has invalid number value
|
|
1185
|
+
*/
|
|
1186
|
+
decimal(key: string, dights?: number, defaultValue?: number): number;
|
|
1187
|
+
/**
|
|
1188
|
+
* Returns `string` when environment key has defined.
|
|
1189
|
+
*
|
|
1190
|
+
* Returns `defaultValue` when environment key is not defined
|
|
1191
|
+
*/
|
|
1192
|
+
string(key: string, defaultValue?: string): string;
|
|
1193
|
+
/**
|
|
1194
|
+
* Returns `array` of parsed environment value.
|
|
1195
|
+
*
|
|
1196
|
+
* Returns `defaultValue` when key is not defined
|
|
1197
|
+
*/
|
|
1198
|
+
list<T extends ListTypeName>(key: string, itemType: T, defaultValue?: ListTypeNameToType<T>[]): ListTypeNameToType<T>[];
|
|
1199
|
+
/**
|
|
1200
|
+
* Returns parsed json value.
|
|
1201
|
+
*
|
|
1202
|
+
* Returns `defaultValue` when key is not defined or invalid json value
|
|
1203
|
+
*/
|
|
1204
|
+
json<T = any>(key: string, defaultValue?: T | null): T | null;
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* Ready-to-use environment parser.
|
|
1208
|
+
*
|
|
1209
|
+
* Target: `process.env`
|
|
1210
|
+
*
|
|
1211
|
+
* Fallback: `import.meta.env`
|
|
1212
|
+
*
|
|
1213
|
+
* @example
|
|
1214
|
+
*
|
|
1215
|
+
* // env.string
|
|
1216
|
+
* const API_KEY = env.string('API_KEY', 'test_key');
|
|
1217
|
+
*
|
|
1218
|
+
* // env.bool
|
|
1219
|
+
* const TEST_FEATURE = env.bool('TEST_FEATURE', false);
|
|
1220
|
+
*
|
|
1221
|
+
* // env.int
|
|
1222
|
+
* const RETRY_ATTEMPTS = env.int('RETRY_ATTEMPTS', 5);
|
|
1223
|
+
*
|
|
1224
|
+
* // env.decimal
|
|
1225
|
+
* const DELAY_SECONDS = env.decimal('DELAY_SECONDS', 2, 5); // round to 2 dights
|
|
1226
|
+
*
|
|
1227
|
+
* // env.list
|
|
1228
|
+
* const TARGET_ROLES = env.list('TARGET_ROLES', 'string', ['ADMIN']);
|
|
1229
|
+
*
|
|
1230
|
+
* // env.json
|
|
1231
|
+
* const GOOGLE_CREDS = env.json<{ projectId: string; token: string; }>('GOOGLE_CREDS');
|
|
1232
|
+
*
|
|
1233
|
+
* @group Environment
|
|
1234
|
+
*/
|
|
1235
|
+
declare const env: Readonly<EnvParser>;
|
|
1236
|
+
/**
|
|
1237
|
+
* @example
|
|
1238
|
+
* const env = createEnvParser(process.env);
|
|
1239
|
+
* // const env = createEnvParser(import.meta.env);
|
|
1240
|
+
*
|
|
1241
|
+
* const API_KEY = env.string('API_KEY', 'test_key');
|
|
1242
|
+
*
|
|
1243
|
+
* @group Environment
|
|
1244
|
+
*/
|
|
1245
|
+
declare function createEnvParser(targetObject: Record<string, string> | Dict<string>): Readonly<EnvParser>;
|
|
1246
|
+
|
|
1247
|
+
/**
|
|
1248
|
+
* Simple application error class with the code
|
|
1249
|
+
* @group Errors
|
|
1250
|
+
*/
|
|
1251
|
+
declare class AppError extends Error {
|
|
1252
|
+
code: number;
|
|
1253
|
+
constructor(messageOrCode: string | number, code?: number, options?: ErrorOptions);
|
|
1254
|
+
/**
|
|
1255
|
+
* alias for `code` property
|
|
1256
|
+
*/
|
|
1257
|
+
get statusCode(): number;
|
|
1258
|
+
get name(): string;
|
|
1259
|
+
static is(value: any): value is AppError;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
/**
|
|
1263
|
+
* Same as `AssertionError` but for browser env.
|
|
1264
|
+
* @group Errors
|
|
1265
|
+
*/
|
|
1266
|
+
declare class BrowserAssertionError extends Error {
|
|
1267
|
+
/**
|
|
1268
|
+
* Set to the `actual` argument for methods such as {@link assert.strictEqual()}.
|
|
1269
|
+
*/
|
|
1270
|
+
actual: unknown;
|
|
1271
|
+
/**
|
|
1272
|
+
* Set to the `expected` argument for methods such as {@link assert.strictEqual()}.
|
|
1273
|
+
*/
|
|
1274
|
+
expected: unknown;
|
|
1275
|
+
/**
|
|
1276
|
+
* Set to the passed in operator value.
|
|
1277
|
+
*/
|
|
1278
|
+
operator: string;
|
|
1279
|
+
/**
|
|
1280
|
+
* Indicates if the message was auto-generated (`true`) or not.
|
|
1281
|
+
*/
|
|
1282
|
+
generatedMessage: boolean;
|
|
1283
|
+
/**
|
|
1284
|
+
* Value is always `ERR_ASSERTION` to show that the error is an assertion error.
|
|
1285
|
+
*/
|
|
1286
|
+
code: 'ERR_ASSERTION';
|
|
1287
|
+
constructor(options?: {
|
|
1288
|
+
/** If provided, the error message is set to this value. */
|
|
1289
|
+
message?: string | undefined;
|
|
1290
|
+
/** The `actual` property on the error instance. */
|
|
1291
|
+
actual?: unknown | undefined;
|
|
1292
|
+
/** The `expected` property on the error instance. */
|
|
1293
|
+
expected?: unknown | undefined;
|
|
1294
|
+
/** The `operator` property on the error instance. */
|
|
1295
|
+
operator?: string | undefined;
|
|
1296
|
+
/** If provided, the generated stack trace omits frames before this function. */
|
|
1297
|
+
stackStartFn?: Function | undefined;
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
/**
|
|
1302
|
+
* @group Utility Functions
|
|
1303
|
+
*/
|
|
1304
|
+
declare function isSuccess<T extends ExecResult>(value: T): value is ExecResultToSuccess<T>;
|
|
1305
|
+
/**
|
|
1306
|
+
* @group Utility Functions
|
|
1307
|
+
*/
|
|
1308
|
+
declare function isSkip<T extends ExecResult>(value: T): value is ExecResultToSkip<T>;
|
|
1309
|
+
|
|
1310
|
+
/**
|
|
1311
|
+
* Extracts file extension from filename or url link
|
|
1312
|
+
*/
|
|
1313
|
+
declare function getFileExtension(name: string, withDot?: boolean): string | null;
|
|
1314
|
+
|
|
1315
|
+
/**
|
|
1316
|
+
* Extract filename from string
|
|
1317
|
+
*
|
|
1318
|
+
* @example
|
|
1319
|
+
* getFileName('Andrew L - CV.pdf'); // 'Andrew L - CV'
|
|
1320
|
+
*
|
|
1321
|
+
* @group Files
|
|
1322
|
+
*/
|
|
1323
|
+
declare function getFileName(value: string): string | null;
|
|
1324
|
+
|
|
1325
|
+
/**
|
|
1326
|
+
* Converts bytes amount into human readably string
|
|
1327
|
+
*
|
|
1328
|
+
* @example
|
|
1329
|
+
* humanFileSize(1024); // 1KB
|
|
1330
|
+
*
|
|
1331
|
+
* @group Files
|
|
1332
|
+
*/
|
|
1333
|
+
declare function humanFileSize(bytes: number, digits?: number, withSpace?: boolean): string;
|
|
1334
|
+
|
|
1335
|
+
/**
|
|
1336
|
+
* Determines if the window object is available in the global scope
|
|
1337
|
+
*
|
|
1338
|
+
* @group Predicates
|
|
1339
|
+
*/
|
|
1340
|
+
declare const isClient: boolean;
|
|
1341
|
+
/**
|
|
1342
|
+
* Returns `true` when value is not `undefined`
|
|
1343
|
+
* @group Predicates
|
|
1344
|
+
*/
|
|
1345
|
+
declare const isDef: <T = any>(val?: T) => val is T;
|
|
1346
|
+
/**
|
|
1347
|
+
* Checks if the given value is a `null` or `undefined`
|
|
1348
|
+
* @group Predicates
|
|
1349
|
+
*/
|
|
1350
|
+
declare function isNullOrUndefined(value: unknown): value is undefined | null;
|
|
1351
|
+
/**
|
|
1352
|
+
* Checks if the given value is a `bigint`
|
|
1353
|
+
* @group Predicates
|
|
1354
|
+
*/
|
|
1355
|
+
declare const isBigInt: (val: any) => val is bigint;
|
|
1356
|
+
/**
|
|
1357
|
+
* Checks if the given value is a `boolean`
|
|
1358
|
+
* @group Predicates
|
|
1359
|
+
*/
|
|
1360
|
+
declare const isBoolean: (val: any) => val is boolean;
|
|
1361
|
+
/**
|
|
1362
|
+
* Checks if the given value is a `function`
|
|
1363
|
+
* @group Predicates
|
|
1364
|
+
*/
|
|
1365
|
+
declare const isFunction: <T extends Function>(val: any) => val is T;
|
|
1366
|
+
/**
|
|
1367
|
+
* Checks if the given value is a `number`
|
|
1368
|
+
*
|
|
1369
|
+
* @example
|
|
1370
|
+
* console.log(isNumber(123)); // true
|
|
1371
|
+
* console.log(isNumber('abc')); // false
|
|
1372
|
+
* console.log(isNumber(NaN)); // false
|
|
1373
|
+
*
|
|
1374
|
+
* @group Predicates
|
|
1375
|
+
*/
|
|
1376
|
+
declare const isNumber: (val: any) => val is number;
|
|
1377
|
+
/**
|
|
1378
|
+
* Checks if the given value is a `string`
|
|
1379
|
+
* @group Predicates
|
|
1380
|
+
*/
|
|
1381
|
+
declare const isString: (val: unknown) => val is string;
|
|
1382
|
+
/**
|
|
1383
|
+
* Checks if the given value is a plain `object`
|
|
1384
|
+
* @group Predicates
|
|
1385
|
+
*/
|
|
1386
|
+
declare const isObject: (val: any) => val is object;
|
|
1387
|
+
/**
|
|
1388
|
+
* Checks if the given value is valid `Date`
|
|
1389
|
+
* @group Predicates
|
|
1390
|
+
*/
|
|
1391
|
+
declare const isDate: (val: any) => val is Date;
|
|
1392
|
+
/**
|
|
1393
|
+
* Function that does nothing
|
|
1394
|
+
* @group Utility Functions
|
|
1395
|
+
*/
|
|
1396
|
+
declare const noop: () => void;
|
|
1397
|
+
/**
|
|
1398
|
+
* Checks if the given value is a `Error`
|
|
1399
|
+
* @group Predicates
|
|
1400
|
+
*/
|
|
1401
|
+
declare const isError: (val: any) => val is Error;
|
|
1402
|
+
/**
|
|
1403
|
+
* Checks if the given value is a `symbol`
|
|
1404
|
+
* @group Predicates
|
|
1405
|
+
*/
|
|
1406
|
+
declare const isSymbol: (val: any) => val is Symbol;
|
|
1407
|
+
/**
|
|
1408
|
+
* Checks if the given value is a `Set`.
|
|
1409
|
+
* @group Predicates
|
|
1410
|
+
*/
|
|
1411
|
+
declare const isSet: <T = any>(val: any) => val is Set<T>;
|
|
1412
|
+
/**
|
|
1413
|
+
* Checks if the given value is a `WeekSet`.
|
|
1414
|
+
* @group Predicates
|
|
1415
|
+
*/
|
|
1416
|
+
declare const isWeakSet: <T extends WeakKey = any>(val: any) => val is WeakSet<T>;
|
|
1417
|
+
/**
|
|
1418
|
+
* Checks if the given value is a `Map`.
|
|
1419
|
+
* @group Predicates
|
|
1420
|
+
*/
|
|
1421
|
+
declare const isMap: <K = any, V = any>(val: any) => val is Map<K, V>;
|
|
1422
|
+
/**
|
|
1423
|
+
* Checks if the given value is a `WeakMap`.
|
|
1424
|
+
* @group Predicates
|
|
1425
|
+
*/
|
|
1426
|
+
declare const isWeakMap: <V = any>(val: any) => val is WeakMap<WeakKey, V>;
|
|
1427
|
+
/**
|
|
1428
|
+
* Checks if two values are equal, including support for `Date`, `RegExp`, and deep object comparison.
|
|
1429
|
+
*
|
|
1430
|
+
* @param {unknown} a - The first value to compare.
|
|
1431
|
+
* @param {unknown} b - The second value to compare.
|
|
1432
|
+
* @returns {boolean} `true` if the values are equal, otherwise `false`.
|
|
1433
|
+
*
|
|
1434
|
+
* @example
|
|
1435
|
+
* isEqual(1, 1); // true
|
|
1436
|
+
* isEqual({ a: 1 }, { a: 1 }); // true
|
|
1437
|
+
* isEqual(/abc/g, /abc/g); // true
|
|
1438
|
+
* isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true
|
|
1439
|
+
* isEqual([1, 2, 3], [1, 2, 3]); // true
|
|
1440
|
+
*
|
|
1441
|
+
* @group Predicates
|
|
1442
|
+
*/
|
|
1443
|
+
declare function isEqual(a: unknown, b: unknown): boolean;
|
|
1444
|
+
/**
|
|
1445
|
+
* Checks if a given value is empty.
|
|
1446
|
+
*
|
|
1447
|
+
* Support for `Array`, `Object`, `string` `Map`, `Set`.
|
|
1448
|
+
*
|
|
1449
|
+
* @example
|
|
1450
|
+
* isEmpty(); // true
|
|
1451
|
+
* isEmpty(null); // true
|
|
1452
|
+
* isEmpty(''); // true
|
|
1453
|
+
* isEmpty([]); // true
|
|
1454
|
+
* isEmpty({}); // true
|
|
1455
|
+
* isEmpty(new Map()); // true
|
|
1456
|
+
* isEmpty(new Set()); // true
|
|
1457
|
+
* isEmpty('hello'); // false
|
|
1458
|
+
* isEmpty([1, 2, 3]); // false
|
|
1459
|
+
* isEmpty({ a: 1 }); // false
|
|
1460
|
+
* isEmpty(new Map([['key', 'value']])); // false
|
|
1461
|
+
* isEmpty(new Set([1, 2, 3])); // false
|
|
1462
|
+
*
|
|
1463
|
+
* @group Predicates
|
|
1464
|
+
*/
|
|
1465
|
+
declare const isEmpty: (obj: any) => boolean;
|
|
1466
|
+
/**
|
|
1467
|
+
* Checks if the given value is a `Promise`
|
|
1468
|
+
* @group Predicates
|
|
1469
|
+
*/
|
|
1470
|
+
declare function isPromise<T = void>(value: any): value is Promise<T>;
|
|
1471
|
+
/**
|
|
1472
|
+
* Checks whether a value is a JavaScript primitive.
|
|
1473
|
+
*
|
|
1474
|
+
* JavaScript primitives include null, undefined, strings, numbers, booleans, symbols, and bigints.
|
|
1475
|
+
* @group Predicates
|
|
1476
|
+
*/
|
|
1477
|
+
declare const isPrimitive: (value: unknown) => value is Primitive;
|
|
1478
|
+
|
|
1479
|
+
/**
|
|
1480
|
+
* Create pretty simple `console.log` wrapper interface.
|
|
1481
|
+
*
|
|
1482
|
+
* @example
|
|
1483
|
+
* const log = logger('UserService');
|
|
1484
|
+
*
|
|
1485
|
+
* log.info('Create user: %s', 'user_1'); // Create user: %s
|
|
1486
|
+
*
|
|
1487
|
+
* @group Utility Functions
|
|
1488
|
+
*/
|
|
1489
|
+
declare const logger: (...baseArgs: any[]) => Logger;
|
|
1490
|
+
|
|
1491
|
+
/**
|
|
1492
|
+
* Check if bits are set in `number` bitmask
|
|
1493
|
+
*
|
|
1494
|
+
* @example
|
|
1495
|
+
* const scope = (1 << 1 | 1 << 2 | 1 << 3);
|
|
1496
|
+
*
|
|
1497
|
+
* checkBitmask(scope, 1 << 2); // true
|
|
1498
|
+
* checkBitmask(scope, 1 << 5); // false
|
|
1499
|
+
*
|
|
1500
|
+
* @group Numbers
|
|
1501
|
+
*/
|
|
1502
|
+
declare function checkBitmask(scope: number, flag: number): boolean;
|
|
1503
|
+
/**
|
|
1504
|
+
* Check if bits are set in `bigint` bitmask
|
|
1505
|
+
*
|
|
1506
|
+
* @example
|
|
1507
|
+
* const scope = (1n << 1n | 1n << 2n | 1n << 3n);
|
|
1508
|
+
*
|
|
1509
|
+
* checkBitmask(scope, 1n << 2n); // true
|
|
1510
|
+
* checkBitmask(scope, 1n << 5n); // false
|
|
1511
|
+
*
|
|
1512
|
+
* @group Numbers
|
|
1513
|
+
*/
|
|
1514
|
+
declare function checkBitmask(scope: bigint, flag: bigint): boolean;
|
|
1515
|
+
|
|
1516
|
+
/**
|
|
1517
|
+
* Rounds the given value to a specified range. If the value is less than the minimum,
|
|
1518
|
+
* it returns the minimum. If the value is greater than the maximum, it returns the maximum.
|
|
1519
|
+
* If the value is within the range, it returns the original value.
|
|
1520
|
+
*
|
|
1521
|
+
* @param {number} num - The number to be clamped.
|
|
1522
|
+
* @param {number} min - The minimum value of the range.
|
|
1523
|
+
* @param {number} max - The maximum value of the range.
|
|
1524
|
+
* @returns {number} - The clamped value within the specified range.
|
|
1525
|
+
*
|
|
1526
|
+
* @example
|
|
1527
|
+
* const min = 5;
|
|
1528
|
+
* const max = 10;
|
|
1529
|
+
*
|
|
1530
|
+
* // Returns: 7 (within range)
|
|
1531
|
+
* clamp(7, min, max);
|
|
1532
|
+
*
|
|
1533
|
+
* // Returns: 10 (clamped to max)
|
|
1534
|
+
* clamp(15, min, max);
|
|
1535
|
+
*
|
|
1536
|
+
* // Returns: 5 (clamped to min)
|
|
1537
|
+
* clamp(3, min, max);
|
|
1538
|
+
*
|
|
1539
|
+
* @group Numbers
|
|
1540
|
+
*/
|
|
1541
|
+
declare const clamp: (num: number, min: number, max: number) => number;
|
|
1542
|
+
|
|
1543
|
+
interface RandomizerOptions {
|
|
1544
|
+
min: number;
|
|
1545
|
+
max: number;
|
|
1546
|
+
pregenerateAmount: number;
|
|
1547
|
+
transform: (value: number) => number;
|
|
1548
|
+
}
|
|
1549
|
+
declare class Randomizer {
|
|
1550
|
+
private _pool;
|
|
1551
|
+
private _step;
|
|
1552
|
+
private _min;
|
|
1553
|
+
private _max;
|
|
1554
|
+
private _pregenerateAmount;
|
|
1555
|
+
private _transform;
|
|
1556
|
+
constructor({ min, max, pregenerateAmount, transform }: RandomizerOptions);
|
|
1557
|
+
/**
|
|
1558
|
+
* Returns the current step of the randomizer.
|
|
1559
|
+
*
|
|
1560
|
+
* @returns {number} The current step.
|
|
1561
|
+
*/
|
|
1562
|
+
getCurrentStep(): number;
|
|
1563
|
+
/**
|
|
1564
|
+
* Sets the current step of the randomizer.
|
|
1565
|
+
*
|
|
1566
|
+
* @param {number} value - The step to set.
|
|
1567
|
+
* @throws {Error} If the provided value is not a valid number or less than 0.
|
|
1568
|
+
*/
|
|
1569
|
+
setCurrentStep(value: number): void;
|
|
1570
|
+
/**
|
|
1571
|
+
* Retrieves a random number either from the current step or a specific step if provided.
|
|
1572
|
+
*
|
|
1573
|
+
* @param {number} [fromStep] - The step from which to retrieve the random number (optional).
|
|
1574
|
+
* @returns {number} The random number at the current or specified step.
|
|
1575
|
+
*/
|
|
1576
|
+
get(fromStep?: number): number;
|
|
1577
|
+
/**
|
|
1578
|
+
* Resets the current step to 0.
|
|
1579
|
+
*/
|
|
1580
|
+
resetStep(): void;
|
|
1581
|
+
/**
|
|
1582
|
+
* Resets the random number pool, clearing and repopulating it with new random values.
|
|
1583
|
+
*/
|
|
1584
|
+
resetPool(): void;
|
|
1585
|
+
private _rand;
|
|
1586
|
+
private _lookup;
|
|
1587
|
+
}
|
|
1588
|
+
/**
|
|
1589
|
+
* Creates a random number generator with step control and optional transformation.
|
|
1590
|
+
* Allows caching of generated numbers for efficiency, with optional pregeneration and transformation.
|
|
1591
|
+
*
|
|
1592
|
+
* @param {RandomizerOptions} options - Configuration for the randomizer.
|
|
1593
|
+
* @param {number} options.min - Minimum value for the random number.
|
|
1594
|
+
* @param {number} options.max - Maximum value for the random number.
|
|
1595
|
+
* @param {number} [options.pregenerateAmount=100] - Number of random numbers to pregenerate and cache.
|
|
1596
|
+
* @param {(value: number) => number} [options.transform] - A function to transform the generated random number.
|
|
1597
|
+
* @returns {Randomizer} - The randomizer object with step control and number generation.
|
|
1598
|
+
*
|
|
1599
|
+
*
|
|
1600
|
+
* @example
|
|
1601
|
+
* // Basic usage of the randomizer
|
|
1602
|
+
* const randomizer = createRandomizer({
|
|
1603
|
+
* min: 1,
|
|
1604
|
+
* max: 10,
|
|
1605
|
+
* pregenerateAmount: 5
|
|
1606
|
+
* });
|
|
1607
|
+
*
|
|
1608
|
+
* // Get the random number at the current step
|
|
1609
|
+
* console.log(randomizer.get()); // e.g., returns 3
|
|
1610
|
+
*
|
|
1611
|
+
* // Get the random number at a specific step
|
|
1612
|
+
* console.log(randomizer.get(2)); // e.g., returns 7
|
|
1613
|
+
*
|
|
1614
|
+
* // Get the current step
|
|
1615
|
+
* console.log(randomizer.getCurrentStep()); // returns the current step (e.g., 1)
|
|
1616
|
+
*
|
|
1617
|
+
* // Set the current step to 3
|
|
1618
|
+
* randomizer.setCurrentStep(3);
|
|
1619
|
+
*
|
|
1620
|
+
* // Get the random number at step 3
|
|
1621
|
+
* console.log(randomizer.get()); // returns the value for step 3
|
|
1622
|
+
*
|
|
1623
|
+
* @example
|
|
1624
|
+
* // Usage with a transformation function
|
|
1625
|
+
* const randomizerWithTransform = createRandomizer({
|
|
1626
|
+
* min: 1,
|
|
1627
|
+
* max: 10,
|
|
1628
|
+
* pregenerateAmount: 5,
|
|
1629
|
+
* transform: (value) => value * 2
|
|
1630
|
+
* });
|
|
1631
|
+
*
|
|
1632
|
+
* // Get a transformed random number at the current step
|
|
1633
|
+
* console.log(randomizerWithTransform.get()); // e.g., returns 6 (original value 3 transformed by multiplying by 2)
|
|
1634
|
+
*
|
|
1635
|
+
* // Reset the step to 0
|
|
1636
|
+
* randomizerWithTransform.resetStep();
|
|
1637
|
+
* console.log(randomizerWithTransform.get()); // returns the random number at step 0
|
|
1638
|
+
*
|
|
1639
|
+
* @group Numbers
|
|
1640
|
+
*/
|
|
1641
|
+
declare function createRandomizer({ min, max, pregenerateAmount, transform, }: Partial<RandomizerOptions>): Randomizer;
|
|
1642
|
+
|
|
1643
|
+
/**
|
|
1644
|
+
* A class that allows you to calculate the running mean (average) of a set of numbers.
|
|
1645
|
+
* It computes the average as new numbers are added and can also reset the progress.
|
|
1646
|
+
*
|
|
1647
|
+
* @example
|
|
1648
|
+
* // Basic usage to calculate running mean
|
|
1649
|
+
* const avg = findMean();
|
|
1650
|
+
* avg.push(1, 2, 3);
|
|
1651
|
+
* console.log(avg.value); // Output: 2 (average of 1, 2, 3)
|
|
1652
|
+
*
|
|
1653
|
+
* @example
|
|
1654
|
+
* // Reset the calculation with an initial value
|
|
1655
|
+
* const avg = findMean(10);
|
|
1656
|
+
* avg.push(20);
|
|
1657
|
+
* console.log(avg.value); // Output: 15 (average of 10, 20)
|
|
1658
|
+
* console.log(avg.count); // Output: 2 (two values added)
|
|
1659
|
+
*/
|
|
1660
|
+
declare class FindMean {
|
|
1661
|
+
#private;
|
|
1662
|
+
constructor(initialValue?: number);
|
|
1663
|
+
/**
|
|
1664
|
+
* Resets the current progress of the mean calculation.
|
|
1665
|
+
* Optionally, you can pass an initial value to start the calculation.
|
|
1666
|
+
*
|
|
1667
|
+
* @param {number} [initialValue] - The initial value to start the mean calculation with.
|
|
1668
|
+
* @returns {FindMean} The current instance of the FindMean class for chaining.
|
|
1669
|
+
*
|
|
1670
|
+
* @example
|
|
1671
|
+
* const avg = findMean();
|
|
1672
|
+
* avg.push(2, 4);
|
|
1673
|
+
* avg.reset();
|
|
1674
|
+
* console.log(avg.value); // Output: 0
|
|
1675
|
+
*/
|
|
1676
|
+
reset(initialValue?: number): FindMean;
|
|
1677
|
+
/**
|
|
1678
|
+
* Retrieves the current mean value (average).
|
|
1679
|
+
*
|
|
1680
|
+
* @returns {number} The current mean value.
|
|
1681
|
+
*
|
|
1682
|
+
* @example
|
|
1683
|
+
* const avg = findMean();
|
|
1684
|
+
* avg.push(5, 10);
|
|
1685
|
+
* console.log(avg.value); // Output: 7.5 (average of 5, 10)
|
|
1686
|
+
*/
|
|
1687
|
+
get value(): number;
|
|
1688
|
+
/**
|
|
1689
|
+
* Retrieves the count of numbers added so far.
|
|
1690
|
+
*
|
|
1691
|
+
* @returns {number} The count of numbers in the set.
|
|
1692
|
+
*
|
|
1693
|
+
* @example
|
|
1694
|
+
* const avg = findMean();
|
|
1695
|
+
* avg.push(10, 20);
|
|
1696
|
+
* console.log(avg.count); // Output: 2
|
|
1697
|
+
*/
|
|
1698
|
+
get count(): number;
|
|
1699
|
+
/**
|
|
1700
|
+
* Adds values to the set and updates the running mean.
|
|
1701
|
+
*
|
|
1702
|
+
* @param {...number} values - The values to add to the set.
|
|
1703
|
+
* @returns {FindMean} The current instance of the FindMean class for chaining.
|
|
1704
|
+
*
|
|
1705
|
+
* @example
|
|
1706
|
+
* const avg = findMean();
|
|
1707
|
+
* avg.push(1, 2, 3);
|
|
1708
|
+
* console.log(avg.value); // Output: 2 (average of 1, 2, 3)
|
|
1709
|
+
* console.log(avg.count); // Output: 3
|
|
1710
|
+
*/
|
|
1711
|
+
push(...values: number[]): FindMean;
|
|
1712
|
+
}
|
|
1713
|
+
/**
|
|
1714
|
+
* Calculate the running mean (average) of a set of numbers.
|
|
1715
|
+
*
|
|
1716
|
+
* @param {number} [value] - An optional starting value for the mean calculation.
|
|
1717
|
+
* @returns {FindMean} A new instance of FindMean class to calculate running mean.
|
|
1718
|
+
*
|
|
1719
|
+
* @example
|
|
1720
|
+
* // Create a FindMean instance and add values to calculate the average
|
|
1721
|
+
* const avg = findMean();
|
|
1722
|
+
* avg.push(3, 3, 3.3);
|
|
1723
|
+
* console.log(avg.value); // Output: 3.1
|
|
1724
|
+
* console.log(avg.count); // Output: 3
|
|
1725
|
+
*
|
|
1726
|
+
* @group Numbers
|
|
1727
|
+
*/
|
|
1728
|
+
declare function findMean(value?: number): FindMean;
|
|
1729
|
+
|
|
1730
|
+
interface FormatNumber {
|
|
1731
|
+
thousands: string;
|
|
1732
|
+
decimal: string;
|
|
1733
|
+
}
|
|
1734
|
+
/**
|
|
1735
|
+
* Formats a number (or string representing a number) into a string with thousands separators and optional decimal points.
|
|
1736
|
+
* The function supports customizing the formatting style using the `FormatNumber` object.
|
|
1737
|
+
*
|
|
1738
|
+
* @param {number | string} value - The number or string to format.
|
|
1739
|
+
* If a string is passed, it is parsed to a number before formatting.
|
|
1740
|
+
* @param {FormatNumber} [format=defaultFormat] - The format settings for thousands and decimal separators.
|
|
1741
|
+
* By default, it uses the `{ thousands: ',', decimal: '.' }`.
|
|
1742
|
+
*
|
|
1743
|
+
* @returns {string} The formatted number string with appropriate thousands separators and decimal formatting.
|
|
1744
|
+
*
|
|
1745
|
+
* @example
|
|
1746
|
+
* // Format a number with default thousands separator
|
|
1747
|
+
* formatNumber(1500);
|
|
1748
|
+
* // Returns: '1,500'
|
|
1749
|
+
*
|
|
1750
|
+
* @example
|
|
1751
|
+
* // Format a number with a custom format (e.g., using a comma as the thousands separator)
|
|
1752
|
+
* formatNumber(1500.75, { thousands: ' ', decimal: '.' });
|
|
1753
|
+
* // Returns: '1 500.75'
|
|
1754
|
+
*
|
|
1755
|
+
* @group Numbers
|
|
1756
|
+
*/
|
|
1757
|
+
declare function formatNumber(value: number | string, format?: FormatNumber): string;
|
|
1758
|
+
|
|
1759
|
+
interface FormatMoney extends FormatNumber {
|
|
1760
|
+
symbol: string;
|
|
1761
|
+
symbolBefore?: boolean;
|
|
1762
|
+
}
|
|
1763
|
+
/**
|
|
1764
|
+
* Formats a given number (amount of money) as a currency string.
|
|
1765
|
+
* This function supports both integer and floating-point representations of money
|
|
1766
|
+
* and automatically applies the appropriate currency formatting for the specified currency code.
|
|
1767
|
+
*
|
|
1768
|
+
* @param {number} amount - The amount of money to format (in cents or as a floating-point value).
|
|
1769
|
+
* @param {string | FormatMoney} formatOrCode - The currency format or the currency code (e.g., 'USD').
|
|
1770
|
+
* If the format is passed as a string, the function will look up the format for that currency code.
|
|
1771
|
+
* @param {boolean} [intMode=false] - When set to `true`, the amount is considered to be in integer form (i.e., cents).
|
|
1772
|
+
* The value will be divided by 100 to convert it to a decimal format.
|
|
1773
|
+
*
|
|
1774
|
+
* @returns {string} The formatted money string, including the currency symbol and the properly formatted number.
|
|
1775
|
+
*
|
|
1776
|
+
* @example
|
|
1777
|
+
* // Basic formatting with USD currency
|
|
1778
|
+
* formatMoney(1500, 'USD');
|
|
1779
|
+
* // Returns: '$1,500'
|
|
1780
|
+
*
|
|
1781
|
+
* @example
|
|
1782
|
+
* // Formatting when the amount is in integer form (representing cents)
|
|
1783
|
+
* formatMoney(1599, 'USD', true);
|
|
1784
|
+
* // Returns: '$15.99'
|
|
1785
|
+
*
|
|
1786
|
+
* @group Numbers
|
|
1787
|
+
*/
|
|
1788
|
+
declare function formatMoney(amount: number, formatOrCode?: string | FormatMoney, intMode?: boolean): string;
|
|
1789
|
+
|
|
1790
|
+
/**
|
|
1791
|
+
* Returns a random integer between min (inclusive) and max (inclusive).
|
|
1792
|
+
* The value is no lower than min (or the next integer greater than min
|
|
1793
|
+
* if min isn't an integer) and no greater than max (or the next integer
|
|
1794
|
+
* lower than max if max isn't an integer).
|
|
1795
|
+
* Using Math.round() will give you a non-uniform distribution!
|
|
1796
|
+
*
|
|
1797
|
+
* @example
|
|
1798
|
+
* getRandomInt(0, 100); // random int between 0 - 100
|
|
1799
|
+
*
|
|
1800
|
+
* @group Numbers
|
|
1801
|
+
*/
|
|
1802
|
+
declare function getRandomInt(min: number, max: number): number;
|
|
1803
|
+
|
|
1804
|
+
/**
|
|
1805
|
+
* Humanizes large numbers into a more readable format using suffixes like K, M, B, T (thousand, million, billion, trillion).
|
|
1806
|
+
*
|
|
1807
|
+
* @param {number | string} input - The number or string to humanize.
|
|
1808
|
+
* If the input is a string, it will be parsed into a number.
|
|
1809
|
+
* @param {number} [decimals=1] - The number of decimal places to display. Default is 1.
|
|
1810
|
+
* @returns {string} A humanized string representation of the number.
|
|
1811
|
+
*
|
|
1812
|
+
* @example
|
|
1813
|
+
* humanize(1000000);
|
|
1814
|
+
* // Returns: '1M'
|
|
1815
|
+
*
|
|
1816
|
+
* @example
|
|
1817
|
+
* humanize(1234567890);
|
|
1818
|
+
* // Returns: '1.2B'
|
|
1819
|
+
*
|
|
1820
|
+
* @example
|
|
1821
|
+
* humanize(9876543210, 2);
|
|
1822
|
+
* // Returns: '9.88B'
|
|
1823
|
+
*
|
|
1824
|
+
* @example
|
|
1825
|
+
* humanize(500);
|
|
1826
|
+
* // Returns: '500'
|
|
1827
|
+
*
|
|
1828
|
+
* @example
|
|
1829
|
+
* humanize('1000000');
|
|
1830
|
+
* // Returns: '1M'
|
|
1831
|
+
*
|
|
1832
|
+
* @group Numbers
|
|
1833
|
+
*/
|
|
1834
|
+
declare function humanize(input: number | string, decimals?: number): string;
|
|
1835
|
+
|
|
1836
|
+
/**
|
|
1837
|
+
* Parses all numbers from a given string and returns them as an array of numbers.
|
|
1838
|
+
* Supports dot decimals and ignores commas unless they appear as part of a number format.
|
|
1839
|
+
* Returns an empty array when the input is invalid or no numbers are found.
|
|
1840
|
+
*
|
|
1841
|
+
* @param {unknown} input - The input value to parse numbers from.
|
|
1842
|
+
* @returns {number[]} - An array of parsed numbers. Returns an empty array if no numbers are found.
|
|
1843
|
+
*
|
|
1844
|
+
* @example
|
|
1845
|
+
* parseAllNumbers("The temperature is -23.5°C and humidity is 60%.");
|
|
1846
|
+
* // Returns: [-23.5, 60]
|
|
1847
|
+
*
|
|
1848
|
+
* @example
|
|
1849
|
+
* parseAllNumbers("No numbers here!");
|
|
1850
|
+
* // Returns: []
|
|
1851
|
+
*
|
|
1852
|
+
* @example
|
|
1853
|
+
* parseAllNumbers(42);
|
|
1854
|
+
* // Returns: [42]
|
|
1855
|
+
*
|
|
1856
|
+
* @example
|
|
1857
|
+
* parseAllNumbers("1,234 and 56.78 are numbers");
|
|
1858
|
+
* // Returns: [1.234, 56.78]
|
|
1859
|
+
*
|
|
1860
|
+
* @example
|
|
1861
|
+
* parseAllNumbers(["Invalid type"]);
|
|
1862
|
+
* // Returns: []
|
|
1863
|
+
*
|
|
1864
|
+
* @group Numbers
|
|
1865
|
+
*/
|
|
1866
|
+
declare function parseAllNumbers(value: unknown): number[];
|
|
1867
|
+
|
|
1868
|
+
/**
|
|
1869
|
+
* Safely parses a percentage value and returns a number between 0 and 100.
|
|
1870
|
+
* It accepts both string and numeric input, automatically handling the '%' sign if present.
|
|
1871
|
+
* If the value is not a valid percentage, it returns 0.
|
|
1872
|
+
*
|
|
1873
|
+
* @param {unknown} value - The value to parse, which can be a string (e.g., '99%') or a number (e.g., 45).
|
|
1874
|
+
* @returns {number} A parsed percentage value, constrained between 0 and 100.
|
|
1875
|
+
* If the input is invalid or cannot be parsed, it returns 0.
|
|
1876
|
+
*
|
|
1877
|
+
* @example
|
|
1878
|
+
* parsePercentage('99%');
|
|
1879
|
+
* // Returns: 99
|
|
1880
|
+
*
|
|
1881
|
+
* @example
|
|
1882
|
+
* parsePercentage('150%');
|
|
1883
|
+
* // Returns: 100 (clamped to the maximum allowed value)
|
|
1884
|
+
*
|
|
1885
|
+
* @example
|
|
1886
|
+
* parsePercentage('50.5%');
|
|
1887
|
+
* // Returns: 50.5
|
|
1888
|
+
*
|
|
1889
|
+
* @example
|
|
1890
|
+
* parsePercentage('abc');
|
|
1891
|
+
* // Returns: 0 (invalid input)
|
|
1892
|
+
*
|
|
1893
|
+
* @example
|
|
1894
|
+
* parsePercentage(80);
|
|
1895
|
+
* // Returns: 80 (valid number input)
|
|
1896
|
+
*
|
|
1897
|
+
* @group Numbers
|
|
1898
|
+
*/
|
|
1899
|
+
declare function parsePercentage(value: unknown): number;
|
|
1900
|
+
|
|
1901
|
+
/**
|
|
1902
|
+
* Calculates the specified percentage of a given value.
|
|
1903
|
+
* The result is the value multiplied by the percentage divided by 100.
|
|
1904
|
+
* Optionally rounds the result to a specified number of decimal places.
|
|
1905
|
+
*
|
|
1906
|
+
* @param {number} value - The value from which the percentage will be calculated.
|
|
1907
|
+
* @param {number} percent - The percentage to calculate from the value.
|
|
1908
|
+
* @param {number} [digits] - Optional. The number of decimal places to round the result to. If not provided, the result will not be rounded.
|
|
1909
|
+
* @returns {number} The calculated percentage of the value. If `digits` is provided, the result is rounded to the specified decimal places.
|
|
1910
|
+
*
|
|
1911
|
+
* @example
|
|
1912
|
+
* percentOf(200, 20);
|
|
1913
|
+
* // Returns: 40 (20% of 200)
|
|
1914
|
+
*
|
|
1915
|
+
* @example
|
|
1916
|
+
* percentOf(200, 20, 2);
|
|
1917
|
+
* // Returns: 40.00 (20% of 200 rounded to 2 decimal places)
|
|
1918
|
+
*
|
|
1919
|
+
* @example
|
|
1920
|
+
* percentOf(150, 15);
|
|
1921
|
+
* // Returns: 22.5 (15% of 150)
|
|
1922
|
+
*
|
|
1923
|
+
* @example
|
|
1924
|
+
* percentOf(1000, 10, 1);
|
|
1925
|
+
* // Returns: 100.0 (10% of 1000 rounded to 1 decimal place)
|
|
1926
|
+
*
|
|
1927
|
+
* @group Numbers
|
|
1928
|
+
*/
|
|
1929
|
+
declare function percentOf(value: number, percent: number, digits?: number): number;
|
|
1930
|
+
|
|
1931
|
+
/**
|
|
1932
|
+
* Rounds a given number to a specified number of decimal places.
|
|
1933
|
+
* The rounding is done using a method that shifts the decimal point, rounds the number, and then shifts it back.
|
|
1934
|
+
*
|
|
1935
|
+
* @param {number} value - The number to be rounded.
|
|
1936
|
+
* @param {number} [digits=2] - The number of decimal places to round to. Defaults to 2 if not provided.
|
|
1937
|
+
* @returns {number} The rounded number with the specified number of decimal places.
|
|
1938
|
+
*
|
|
1939
|
+
* @example
|
|
1940
|
+
* round2digits(3.3333333, 1);
|
|
1941
|
+
* // Returns: 3.3
|
|
1942
|
+
*
|
|
1943
|
+
* @example
|
|
1944
|
+
* round2digits(3.3333333, 2);
|
|
1945
|
+
* // Returns: 3.33
|
|
1946
|
+
*
|
|
1947
|
+
* @example
|
|
1948
|
+
* round2digits(3.3333333, 3);
|
|
1949
|
+
* // Returns: 3.333
|
|
1950
|
+
*
|
|
1951
|
+
* @example
|
|
1952
|
+
* round2digits(3.789, 0);
|
|
1953
|
+
* // Returns: 4 (rounded to the nearest integer)
|
|
1954
|
+
*
|
|
1955
|
+
* @group Numbers
|
|
1956
|
+
*/
|
|
1957
|
+
declare function round2digits(value: number, digits?: number): number;
|
|
1958
|
+
|
|
1959
|
+
/**
|
|
1960
|
+
* Returns the number of seconds since the Unix epoch (January 1, 1970).
|
|
1961
|
+
*
|
|
1962
|
+
* This function accepts either a `Date` object or a timestamp in milliseconds (number).
|
|
1963
|
+
* If no argument is provided, it defaults to the current timestamp in seconds.
|
|
1964
|
+
*
|
|
1965
|
+
* @param {Date | number} [fromValue=Date.now()] - The date or timestamp to convert.
|
|
1966
|
+
* If not provided, the current date and time will be used.
|
|
1967
|
+
*
|
|
1968
|
+
* @returns {number} The number of seconds since the Unix epoch for the provided date or timestamp.
|
|
1969
|
+
*
|
|
1970
|
+
* @example
|
|
1971
|
+
* // Using a Date object
|
|
1972
|
+
* const date = new Date('2020-01-01T00:00:00Z');
|
|
1973
|
+
* console.log(timestamp(date)); // Returns 1577836800 (seconds since Unix epoch)
|
|
1974
|
+
*
|
|
1975
|
+
* // Using a timestamp in milliseconds
|
|
1976
|
+
* const timestampInMs = 1609459200000;
|
|
1977
|
+
* console.log(timestamp(timestampInMs)); // Returns 1609459200 (seconds since Unix epoch)
|
|
1978
|
+
*
|
|
1979
|
+
* // Using the current time
|
|
1980
|
+
* console.log(timestamp()); // Returns current seconds since Unix epoch
|
|
1981
|
+
*
|
|
1982
|
+
* @group Numbers
|
|
1983
|
+
*/
|
|
1984
|
+
declare function timestamp(fromValue?: Date | number): number;
|
|
1985
|
+
|
|
1986
|
+
/**
|
|
1987
|
+
* Converts a Unix timestamp (in seconds) to a `Date` object.
|
|
1988
|
+
*
|
|
1989
|
+
* This function accepts a timestamp in seconds (number) and returns a `Date` object
|
|
1990
|
+
* corresponding to that timestamp. If an invalid number is passed (non-numeric or NaN),
|
|
1991
|
+
* it returns `null`.
|
|
1992
|
+
*
|
|
1993
|
+
* @param {number} value - The Unix timestamp (in seconds) to convert into a `Date` object.
|
|
1994
|
+
* @returns {Date | null} The `Date` object corresponding to the provided timestamp, or `null`
|
|
1995
|
+
* if the value is not a valid number.
|
|
1996
|
+
*
|
|
1997
|
+
* @example
|
|
1998
|
+
* const date = timestampToDate(1609459200);
|
|
1999
|
+
* console.log(date); // Outputs: Thu Jan 01 2021 00:00:00 GMT+0000 (UTC)
|
|
2000
|
+
*
|
|
2001
|
+
* // Invalid input
|
|
2002
|
+
* console.log(timestampToDate('invalid')); // Outputs: null
|
|
2003
|
+
* console.log(timestampToDate(NaN)); // Outputs: null
|
|
2004
|
+
* console.log(timestampToDate(null)); // Outputs: null
|
|
2005
|
+
*
|
|
2006
|
+
* @group Numbers
|
|
2007
|
+
*/
|
|
2008
|
+
declare function timestampToDate(value: number): Date | null;
|
|
2009
|
+
|
|
2010
|
+
/**
|
|
2011
|
+
* Removes properties with empty values from an object.
|
|
2012
|
+
*
|
|
2013
|
+
* This function iterates over the object's keys and deletes any property whose value
|
|
2014
|
+
* is considered "empty" (e.g., `null`, `undefined`, `[]`, `{}`, `''`, `false`).
|
|
2015
|
+
*
|
|
2016
|
+
* ⚠️ **Mutates the original object**: The input object is directly modified, and properties
|
|
2017
|
+
* are removed from it.
|
|
2018
|
+
*
|
|
2019
|
+
* @param {Record<string, any>} obj - The object to clean up, where empty fields will be removed.
|
|
2020
|
+
* @returns {Record<string, any>} The cleaned object with empty fields removed.
|
|
2021
|
+
*
|
|
2022
|
+
* @example
|
|
2023
|
+
* const user = { id: 1, name: 'Andrew', roles: [], address: null };
|
|
2024
|
+
* cleanEmpty(user);
|
|
2025
|
+
*
|
|
2026
|
+
* console.log(user); // Outputs: { id: 1, name: 'Andrew' }
|
|
2027
|
+
*
|
|
2028
|
+
* @example
|
|
2029
|
+
* const product = { name: 'Laptop', description: '', price: 1000, tags: [] };
|
|
2030
|
+
* cleanEmpty(product);
|
|
2031
|
+
*
|
|
2032
|
+
* console.log(product); // Outputs: { name: 'Laptop', price: 1000 }
|
|
2033
|
+
*
|
|
2034
|
+
* @group Object
|
|
2035
|
+
*/
|
|
2036
|
+
declare function cleanEmpty(obj: Record<any, any>): Record<any, any>;
|
|
2037
|
+
|
|
2038
|
+
/**
|
|
2039
|
+
* Removes all properties from the given object, including symbol keys.
|
|
2040
|
+
*
|
|
2041
|
+
* This function deletes all enumerable properties, both string and symbol keys, from the
|
|
2042
|
+
* input object. The object is directly mutated by this operation.
|
|
2043
|
+
*
|
|
2044
|
+
* ⚠️ **Mutates the original object**: The function modifies the input object in place.
|
|
2045
|
+
*
|
|
2046
|
+
* ⚠️ **Removes symbol keys**: Symbol-based keys are also deleted, unlike typical object
|
|
2047
|
+
* iteration methods.
|
|
2048
|
+
*
|
|
2049
|
+
* @param {Record<string, any>} input - The object to clean up. After execution, it will be empty.
|
|
2050
|
+
* @returns {void} This function does not return a value, as it mutates the input object directly.
|
|
2051
|
+
*
|
|
2052
|
+
* @example
|
|
2053
|
+
* const user = { id: 1, name: 'Andrew', roles: [], [Symbol('unique')]: 'symbolValue' };
|
|
2054
|
+
* cleanObject(user);
|
|
2055
|
+
*
|
|
2056
|
+
* console.log(user); // Outputs: {}
|
|
2057
|
+
*
|
|
2058
|
+
* @example
|
|
2059
|
+
* const settings = { theme: 'dark', [Symbol('private')]: 'secret' };
|
|
2060
|
+
* cleanObject(settings);
|
|
2061
|
+
*
|
|
2062
|
+
* console.log(settings); // Outputs: {}
|
|
2063
|
+
*
|
|
2064
|
+
* @group Object
|
|
2065
|
+
*/
|
|
2066
|
+
declare const cleanObject: (input: Record<string, any>) => void;
|
|
2067
|
+
|
|
2068
|
+
/**
|
|
2069
|
+
* Performs a deep merge of the source object into the destination object.
|
|
2070
|
+
*
|
|
2071
|
+
* This function recursively copies properties from the source object to the destination object.
|
|
2072
|
+
* If a property is an object itself, it will recursively merge its properties. Otherwise,
|
|
2073
|
+
* the value will be directly assigned to the destination object.
|
|
2074
|
+
*
|
|
2075
|
+
* ⚠️ **Mutates the destination object**: The destination object is modified in place.
|
|
2076
|
+
*
|
|
2077
|
+
* @param {object} dest - The target object that will be modified with properties from the source.
|
|
2078
|
+
* @param {object} source - The source object whose properties will be copied to the destination.
|
|
2079
|
+
* @returns {void} This function does not return a value, as it mutates the destination object.
|
|
2080
|
+
*
|
|
2081
|
+
* @example
|
|
2082
|
+
* const user = {
|
|
2083
|
+
* id: 1,
|
|
2084
|
+
* name: 'Andrew',
|
|
2085
|
+
* data: { a: 1, b: 2 },
|
|
2086
|
+
* };
|
|
2087
|
+
*
|
|
2088
|
+
* deepAssign(user, { data: { c: 3 } });
|
|
2089
|
+
*
|
|
2090
|
+
* console.log(user);
|
|
2091
|
+
* // Outputs: '{ id: 1, name: 'Andrew', data: { a: 1, b: 2, c: 3 } }'
|
|
2092
|
+
*
|
|
2093
|
+
* @example
|
|
2094
|
+
* const config = { theme: { dark: true }, version: '1.0' };
|
|
2095
|
+
* const updates = { theme: { light: false }, version: '2.0' };
|
|
2096
|
+
*
|
|
2097
|
+
* deepAssign(config, updates);
|
|
2098
|
+
*
|
|
2099
|
+
* console.log(config);
|
|
2100
|
+
* // Outputs: '{ theme: { dark: true, light: false }, version: '2.0' }'
|
|
2101
|
+
*
|
|
2102
|
+
* @group Object
|
|
2103
|
+
*/
|
|
2104
|
+
declare const deepAssign: (dest: object, source: object) => void;
|
|
2105
|
+
|
|
2106
|
+
/**
|
|
2107
|
+
* Recursively clones the provided value, creating a deep copy.
|
|
2108
|
+
*
|
|
2109
|
+
* This function performs a deep clone of the provided value. Any nested objects, arrays, or other complex types will be cloned recursively,
|
|
2110
|
+
* ensuring that the original value and the cloned value are completely independent.
|
|
2111
|
+
*
|
|
2112
|
+
* @param {T} value - The value to recursively clone. Can be any type (object, array, primitive, etc.).
|
|
2113
|
+
* @returns {T} Returns a new deeply cloned instance of the original value.
|
|
2114
|
+
*
|
|
2115
|
+
* @example
|
|
2116
|
+
* const original = { name: 'Alice', details: { age: 25, country: 'Wonderland' } };
|
|
2117
|
+
* const cloned = deepClone(original);
|
|
2118
|
+
*
|
|
2119
|
+
* cloned.details.age = 30;
|
|
2120
|
+
* console.log(original.details.age); // 25
|
|
2121
|
+
* console.log(cloned.details.age); // 30
|
|
2122
|
+
*
|
|
2123
|
+
* @example
|
|
2124
|
+
* const arr = [1, [2, 3], 4];
|
|
2125
|
+
* const clonedArr = deepClone(arr);
|
|
2126
|
+
* clonedArr[1][0] = 99;
|
|
2127
|
+
* console.log(arr[1][0]); // 2
|
|
2128
|
+
* console.log(clonedArr[1][0]); // 99
|
|
2129
|
+
*
|
|
2130
|
+
* @group Object
|
|
2131
|
+
*/
|
|
2132
|
+
declare const deepClone: <T>(value: T) => T;
|
|
2133
|
+
|
|
2134
|
+
type WithCustomizer = (value: any, key: number | string | undefined) => any;
|
|
2135
|
+
type WithCustomizerFactory = () => WithCustomizer;
|
|
2136
|
+
type WithCustomizerValue = Readonly<Arrayable<WithCustomizer | WithCustomizerFactory>>;
|
|
2137
|
+
/**
|
|
2138
|
+
* Recursively clones the provided value with a customizer function that allows for transformation of certain values during the cloning process.
|
|
2139
|
+
*
|
|
2140
|
+
* This function deep clones the value while providing a way to customize the cloning behavior of certain properties or elements.
|
|
2141
|
+
* The `customizer` function will be called for each value being cloned, and if the customizer function returns a value other than `undefined`,
|
|
2142
|
+
* the original value will be replaced with the returned value. This allows for specific modifications to parts of the structure being cloned.
|
|
2143
|
+
*
|
|
2144
|
+
* @param {T} value - The value to recursively clone. Can be any type (object, array, primitive, etc.).
|
|
2145
|
+
* @param {WithCustomizerValue} customizer - A function to customize the cloning process. It receives the current value and key, and must return
|
|
2146
|
+
* either a modified value or `undefined` (to keep the original value).
|
|
2147
|
+
*
|
|
2148
|
+
* @returns {T} Returns a new deep clone of the original value, with customizations applied as per the `customizer` function.
|
|
2149
|
+
*
|
|
2150
|
+
* @example
|
|
2151
|
+
* const original = { name: 'Alice', age: 30, details: { country: 'Wonderland', city: 'London' } };
|
|
2152
|
+
*
|
|
2153
|
+
* const customizer = (value, key) => {
|
|
2154
|
+
* if (key === 'city') return 'Paris'; // Customizing the 'city' field to 'Paris'.
|
|
2155
|
+
* };
|
|
2156
|
+
*
|
|
2157
|
+
* const cloned = deepCloneWith(original, customizer);
|
|
2158
|
+
* console.log(cloned.details.city); // 'Paris'
|
|
2159
|
+
* console.log(original.details.city); // 'London' (original is unchanged)
|
|
2160
|
+
*
|
|
2161
|
+
* @example
|
|
2162
|
+
* const arr = [1, [2, 3], 4];
|
|
2163
|
+
*
|
|
2164
|
+
* const customizer = (value) => {
|
|
2165
|
+
* if (Array.isArray(value)) return value.map(item => item * 2); // Doubling the numbers inside arrays.
|
|
2166
|
+
* };
|
|
2167
|
+
*
|
|
2168
|
+
* const clonedArr = deepCloneWith(arr, customizer);
|
|
2169
|
+
* console.log(clonedArr); // [1, [4, 6], 4]
|
|
2170
|
+
* console.log(arr); // [1, [2, 3], 4] (original is unchanged)
|
|
2171
|
+
*
|
|
2172
|
+
* @group Object
|
|
2173
|
+
*/
|
|
2174
|
+
declare function deepCloneWith<T>(value: T, customizer: WithCustomizerValue): T;
|
|
2175
|
+
declare function createDeepCloneWith(customizer: WithCustomizerValue): <T>(value: T) => T;
|
|
2176
|
+
declare function isCustomizerFactory(value: unknown): value is WithCustomizerFactory;
|
|
2177
|
+
declare function createCustomizer(fn: WithCustomizer): WithCustomizer;
|
|
2178
|
+
declare function createCustomizerFactory(fn: (...args: any[]) => WithCustomizer): WithCustomizerFactory;
|
|
2179
|
+
declare function createSecureCustomizer(properties: string[]): WithCustomizerFactory;
|
|
2180
|
+
|
|
2181
|
+
/**
|
|
2182
|
+
* Recursively assigns default properties.
|
|
2183
|
+
* @param object The destination object.
|
|
2184
|
+
* @param sources The source objects.
|
|
2185
|
+
* @return Returns object.
|
|
2186
|
+
*
|
|
2187
|
+
* @example
|
|
2188
|
+
* const obj = { name: 'Alice', age: 30 };
|
|
2189
|
+
* const defaults = { name: 'Bob', age: 25, country: 'Wonderland' };
|
|
2190
|
+
*
|
|
2191
|
+
* deepDefaults(obj, defaults);
|
|
2192
|
+
* console.log(obj);
|
|
2193
|
+
* // Output: { name: 'Alice', age: 30, country: 'Wonderland' }
|
|
2194
|
+
* // The 'name' and 'age' properties are not overwritten since they already exist.
|
|
2195
|
+
*
|
|
2196
|
+
* @example
|
|
2197
|
+
* const obj = { user: { name: 'Alice' } };
|
|
2198
|
+
* const defaults = { user: { age: 25 } };
|
|
2199
|
+
*
|
|
2200
|
+
* deepDefaults(obj, defaults);
|
|
2201
|
+
* console.log(obj);
|
|
2202
|
+
* // Output: { user: { name: 'Alice', age: 25 } }
|
|
2203
|
+
* // The 'age' property is added to 'user', while 'name' remains unchanged.
|
|
2204
|
+
*
|
|
2205
|
+
* @group Object
|
|
2206
|
+
*/
|
|
2207
|
+
declare const deepDefaults: (object: any, ...sources: any[]) => any;
|
|
2208
|
+
|
|
2209
|
+
/**
|
|
2210
|
+
* Recursively freezes an object or array, making it immutable at all levels.
|
|
2211
|
+
*
|
|
2212
|
+
* This function is similar to `Object.freeze()`, but instead of freezing only the top-level
|
|
2213
|
+
* properties of an object, it recursively freezes every nested object or array, ensuring
|
|
2214
|
+
* that no properties or elements can be modified at any depth.
|
|
2215
|
+
*
|
|
2216
|
+
* **Important**:
|
|
2217
|
+
* - Once frozen, attempting to modify any property or element of the object will result in an error in strict mode.
|
|
2218
|
+
* - If a property of an object or an element of an array is itself an object, it will also be frozen.
|
|
2219
|
+
*
|
|
2220
|
+
* @param {T} value - The object or array to freeze deeply.
|
|
2221
|
+
* @returns {T} The frozen object or array, which is also deeply immutable.
|
|
2222
|
+
*
|
|
2223
|
+
* @example
|
|
2224
|
+
* const config = deepFreeze({
|
|
2225
|
+
* db: { uri: '' },
|
|
2226
|
+
* });
|
|
2227
|
+
*
|
|
2228
|
+
* config.db.uri = 'test'; // Error: Cannot assign to read-only property 'uri' of object
|
|
2229
|
+
*
|
|
2230
|
+
* @example
|
|
2231
|
+
* const arr = deepFreeze([ { name: 'Alice' }, { name: 'Bob' } ]);
|
|
2232
|
+
* arr[0].name = 'Charlie'; // Error: Cannot assign to read-only property 'name' of object
|
|
2233
|
+
*
|
|
2234
|
+
* @group Object
|
|
2235
|
+
*/
|
|
2236
|
+
declare function deepFreeze<T extends object | unknown[]>(value: T): T;
|
|
2237
|
+
|
|
2238
|
+
/**
|
|
2239
|
+
* Define not enumerable property in object.
|
|
2240
|
+
*
|
|
2241
|
+
* @example
|
|
2242
|
+
* const USER_SYM = Symbol();
|
|
2243
|
+
* const user = { id: 1, name: 'Andrew' };
|
|
2244
|
+
*
|
|
2245
|
+
* // define hidden marker
|
|
2246
|
+
* def(user, USER_SYM, true);
|
|
2247
|
+
*
|
|
2248
|
+
* console.log(user[USER_SYM] === true); // true
|
|
2249
|
+
*
|
|
2250
|
+
* @group Object
|
|
2251
|
+
*/
|
|
2252
|
+
declare const def: (obj: object, key: string | symbol, value: any, writable?: boolean) => void;
|
|
2253
|
+
|
|
2254
|
+
/**
|
|
2255
|
+
* @example
|
|
2256
|
+
* const PERMISSIONS = {
|
|
2257
|
+
* USER_CREATE: 1 << 0,
|
|
2258
|
+
* USER_UPDATE: 1 << 1,
|
|
2259
|
+
* USER_DELETE: 1 << 2,
|
|
2260
|
+
* USER_LIST: 1 << 4,
|
|
2261
|
+
* } as const;
|
|
2262
|
+
*
|
|
2263
|
+
* const scope = PERMISSIONS.USER_CREATE | PERMISSIONS.USER_LIST;
|
|
2264
|
+
*
|
|
2265
|
+
* // { USER_CREATE: true, USER_UPDATE: false, USER_DELETE: false, USER_LIST: true }
|
|
2266
|
+
* const flags = flagsToMap(scope, PERMISSIONS);
|
|
2267
|
+
*/
|
|
2268
|
+
declare function flagsToMap(value: number, bitmaskMap: Record<string, number>): Record<string, boolean>;
|
|
2269
|
+
declare function flagsToMap(value: bigint, bitmaskMap: Record<string, bigint>): Record<string, boolean>;
|
|
2270
|
+
|
|
2271
|
+
interface FlattenOptions {
|
|
2272
|
+
/**
|
|
2273
|
+
* Character to separate the flattened keys
|
|
2274
|
+
*/
|
|
2275
|
+
separator?: string;
|
|
2276
|
+
/**
|
|
2277
|
+
* Prefix to add to the flattened keys
|
|
2278
|
+
*/
|
|
2279
|
+
initialPrefix?: string;
|
|
2280
|
+
/**
|
|
2281
|
+
* Whether to include arrays in the flattened result
|
|
2282
|
+
*/
|
|
2283
|
+
withArrays?: boolean;
|
|
2284
|
+
/**
|
|
2285
|
+
* Custom function to check if a value is an object
|
|
2286
|
+
*/
|
|
2287
|
+
isObjectCompare?: (value: unknown) => boolean;
|
|
2288
|
+
}
|
|
2289
|
+
/**
|
|
2290
|
+
* Flattens a nested object into a single-level object, converting nested properties
|
|
2291
|
+
* into key-value pairs with keys representing the property path.
|
|
2292
|
+
*
|
|
2293
|
+
* By default, nested objects are flattened with an underscore (`_`) separator.
|
|
2294
|
+
* Arrays can also be flattened into indexed keys. A custom function can be provided
|
|
2295
|
+
* to determine if a value should be treated as an object.
|
|
2296
|
+
*
|
|
2297
|
+
* **Important**:
|
|
2298
|
+
* - Nested objects are flattened with keys joined by the `separator` (default: `_`).
|
|
2299
|
+
* - Arrays are flattened by their indices (e.g., `array[0]` becomes `array_0`).
|
|
2300
|
+
* - A custom `isObjectCompare` function can be provided to determine whether a value
|
|
2301
|
+
* should be treated as an object.
|
|
2302
|
+
*
|
|
2303
|
+
* @param {Record<string, unknown>} obj - The object to flatten.
|
|
2304
|
+
* @param {FlattenOptions} options - Optional configuration for flattening behavior.
|
|
2305
|
+
* @param {string} [options.separator='_'] - Separator for flattening object keys (default is '_').
|
|
2306
|
+
* @param {string} [options.initialPrefix=''] - Prefix to prepend to flattened keys (default is '').
|
|
2307
|
+
* @param {boolean} [options.withArrays=true] - Whether to include arrays in the flattened result (default is true).
|
|
2308
|
+
* @param {(value: unknown) => boolean} [options.isObjectCompare=isObject] - Custom function to check if a value is an object.
|
|
2309
|
+
* @returns {Record<string, unknown>} - The flattened object.
|
|
2310
|
+
*
|
|
2311
|
+
* @example
|
|
2312
|
+
* flatten({
|
|
2313
|
+
* name: 'Andrew',
|
|
2314
|
+
* config: {
|
|
2315
|
+
* canReadPost: true,
|
|
2316
|
+
* canUpdatePost: true,
|
|
2317
|
+
* }
|
|
2318
|
+
* });
|
|
2319
|
+
* // Result:
|
|
2320
|
+
* // {
|
|
2321
|
+
* // 'name': 'Andrew',
|
|
2322
|
+
* // 'config_canReadPost': true,
|
|
2323
|
+
* // 'config_canUpdatePost': true,
|
|
2324
|
+
* // }
|
|
2325
|
+
*
|
|
2326
|
+
* @example
|
|
2327
|
+
* flatten(
|
|
2328
|
+
* { user: { name: 'Jane', profile: { age: 30 } } },
|
|
2329
|
+
* { separator: '-', initialPrefix: 'root-' }
|
|
2330
|
+
* );
|
|
2331
|
+
* // Returns:
|
|
2332
|
+
* // { 'root-user-name': 'Jane', 'root-user-profile-age': 30 }
|
|
2333
|
+
*
|
|
2334
|
+
* @group Object
|
|
2335
|
+
*/
|
|
2336
|
+
declare function flatten(obj: Record<string, unknown>, { separator, initialPrefix, withArrays, isObjectCompare, }?: FlattenOptions): Record<string, unknown>;
|
|
2337
|
+
|
|
2338
|
+
/**
|
|
2339
|
+
* Get object property by dot notation
|
|
2340
|
+
*
|
|
2341
|
+
* @example
|
|
2342
|
+
* const user = { id: 1, data: { roles: ['admin'] } };
|
|
2343
|
+
* const roles = get(user, 'data.roles');
|
|
2344
|
+
*
|
|
2345
|
+
* console.log(roles) // ['admin']
|
|
2346
|
+
*
|
|
2347
|
+
* @group Object
|
|
2348
|
+
*/
|
|
2349
|
+
declare const get: {
|
|
2350
|
+
<TObject extends object, TKey extends keyof TObject>(object: TObject, path: TKey | [TKey]): TObject[TKey];
|
|
2351
|
+
<TObject extends object, TKey extends keyof TObject>(object: TObject | null | undefined, path: TKey | [TKey]): TObject[TKey] | undefined;
|
|
2352
|
+
<TObject extends object, TKey extends keyof TObject, TDefault>(object: TObject | null | undefined, path: TKey | [TKey], defaultValue: TDefault): Exclude<TObject[TKey], undefined> | TDefault;
|
|
2353
|
+
<TObject extends object, TKey1 extends keyof TObject, TKey2 extends keyof TObject[TKey1]>(object: TObject, path: [TKey1, TKey2]): TObject[TKey1][TKey2];
|
|
2354
|
+
<TObject extends object, TKey1 extends keyof TObject, TKey2 extends keyof NonNullable<TObject[TKey1]>>(object: TObject | null | undefined, path: [TKey1, TKey2]): NonNullable<TObject[TKey1]>[TKey2] | undefined;
|
|
2355
|
+
<TObject extends object, TKey1 extends keyof TObject, TKey2 extends keyof NonNullable<TObject[TKey1]>, TDefault>(object: TObject | null | undefined, path: [TKey1, TKey2], defaultValue: TDefault): Exclude<NonNullable<TObject[TKey1]>[TKey2], undefined> | TDefault;
|
|
2356
|
+
<TObject extends object, TKey1 extends keyof TObject, TKey2 extends keyof TObject[TKey1], TKey3 extends keyof TObject[TKey1][TKey2]>(object: TObject, path: [TKey1, TKey2, TKey3]): TObject[TKey1][TKey2][TKey3];
|
|
2357
|
+
<TObject extends object, TKey1 extends keyof TObject, TKey2 extends keyof NonNullable<TObject[TKey1]>, TKey3 extends keyof NonNullable<NonNullable<TObject[TKey1]>[TKey2]>>(object: TObject | null | undefined, path: [TKey1, TKey2, TKey3]): NonNullable<NonNullable<TObject[TKey1]>[TKey2]>[TKey3] | undefined;
|
|
2358
|
+
<TObject extends object, TKey1 extends keyof TObject, TKey2 extends keyof NonNullable<TObject[TKey1]>, TKey3 extends keyof NonNullable<NonNullable<TObject[TKey1]>[TKey2]>, TDefault>(object: TObject | null | undefined, path: [TKey1, TKey2, TKey3], defaultValue: TDefault): Exclude<NonNullable<NonNullable<TObject[TKey1]>[TKey2]>[TKey3], undefined> | TDefault;
|
|
2359
|
+
<TObject extends object, TKey1 extends keyof TObject, TKey2 extends keyof TObject[TKey1], TKey3 extends keyof TObject[TKey1][TKey2], TKey4 extends keyof TObject[TKey1][TKey2][TKey3]>(object: TObject, path: [TKey1, TKey2, TKey3, TKey4]): TObject[TKey1][TKey2][TKey3][TKey4];
|
|
2360
|
+
<TObject extends object, TKey1 extends keyof TObject, TKey2 extends keyof NonNullable<TObject[TKey1]>, TKey3 extends keyof NonNullable<NonNullable<TObject[TKey1]>[TKey2]>, TKey4 extends keyof NonNullable<NonNullable<NonNullable<TObject[TKey1]>[TKey2]>[TKey3]>>(object: TObject | null | undefined, path: [TKey1, TKey2, TKey3, TKey4]): NonNullable<NonNullable<NonNullable<TObject[TKey1]>[TKey2]>[TKey3]>[TKey4] | undefined;
|
|
2361
|
+
<TObject extends object, TKey1 extends keyof TObject, TKey2 extends keyof NonNullable<TObject[TKey1]>, TKey3 extends keyof NonNullable<NonNullable<TObject[TKey1]>[TKey2]>, TKey4 extends keyof NonNullable<NonNullable<NonNullable<TObject[TKey1]>[TKey2]>[TKey3]>, TDefault>(object: TObject | null | undefined, path: [TKey1, TKey2, TKey3, TKey4], defaultValue: TDefault): Exclude<NonNullable<NonNullable<NonNullable<TObject[TKey1]>[TKey2]>[TKey3]>[TKey4], undefined> | TDefault;
|
|
2362
|
+
<T>(object: lodash.NumericDictionary<T>, path: number): T;
|
|
2363
|
+
<T>(object: lodash.NumericDictionary<T> | null | undefined, path: number): T | undefined;
|
|
2364
|
+
<T, TDefault>(object: lodash.NumericDictionary<T> | null | undefined, path: number, defaultValue: TDefault): T | TDefault;
|
|
2365
|
+
<TDefault>(object: null | undefined, path: lodash.PropertyPath, defaultValue: TDefault): TDefault;
|
|
2366
|
+
(object: null | undefined, path: lodash.PropertyPath): undefined;
|
|
2367
|
+
<TObject, TPath extends string>(data: TObject, path: TPath): string extends TPath ? any : lodash.GetFieldType<TObject, TPath>;
|
|
2368
|
+
<TObject, TPath extends string, TDefault = lodash.GetFieldType<TObject, TPath, "Path">>(data: TObject, path: TPath, defaultValue: TDefault): Exclude<lodash.GetFieldType<TObject, TPath>, null | undefined> | TDefault;
|
|
2369
|
+
(object: any, path: lodash.PropertyPath, defaultValue?: any): any;
|
|
2370
|
+
};
|
|
2371
|
+
|
|
2372
|
+
/**
|
|
2373
|
+
* Returns true when provided keys exists in target object
|
|
2374
|
+
*
|
|
2375
|
+
* @example
|
|
2376
|
+
* const user = { id: 1, name: 'Andrew' };
|
|
2377
|
+
*
|
|
2378
|
+
* has(user, ['roles']); // false
|
|
2379
|
+
* has(user, ['roles', 'name']); // false
|
|
2380
|
+
* has(user, ['name']); // true
|
|
2381
|
+
*
|
|
2382
|
+
* @group Object
|
|
2383
|
+
*/
|
|
2384
|
+
declare function has<T extends PropertyKey>(value: any, keys: T[]): value is {
|
|
2385
|
+
[K in T]: any;
|
|
2386
|
+
};
|
|
2387
|
+
|
|
2388
|
+
/**
|
|
2389
|
+
* Check if object has own property
|
|
2390
|
+
*
|
|
2391
|
+
* @group Object
|
|
2392
|
+
*/
|
|
2393
|
+
declare const hasOwn: <T extends object, K extends keyof T>(val: T, key: K) => key is K;
|
|
2394
|
+
|
|
2395
|
+
/**
|
|
2396
|
+
* Creates a new object with specified keys omitted.
|
|
2397
|
+
*
|
|
2398
|
+
* This function takes an object and an array of keys, and returns a new object that
|
|
2399
|
+
* excludes the properties corresponding to the specified keys.
|
|
2400
|
+
*
|
|
2401
|
+
* @template T - The type of object.
|
|
2402
|
+
* @template K - The type of keys in object.
|
|
2403
|
+
* @param {T} obj - The object to omit keys from.
|
|
2404
|
+
* @param {K[]} keys - An array of keys to be omitted from the object.
|
|
2405
|
+
* @returns {Omit<T, K>} A new object with the specified keys omitted.
|
|
2406
|
+
*
|
|
2407
|
+
* @example
|
|
2408
|
+
* const obj = { a: 1, b: 2, c: 3 };
|
|
2409
|
+
* const result = omit(obj, ['b', 'c']);
|
|
2410
|
+
* // result will be { a: 1 }
|
|
2411
|
+
*
|
|
2412
|
+
* @group Object
|
|
2413
|
+
*/
|
|
2414
|
+
declare function omit<T extends Record<string, any>, U extends keyof T>(obj: T, excludes: Readonly<Array<U> | Set<U> | Array<string> | Set<string>>): Omit<T, U>;
|
|
2415
|
+
|
|
2416
|
+
/**
|
|
2417
|
+
* Pick object keys with excluding prefix keys
|
|
2418
|
+
*
|
|
2419
|
+
* @example
|
|
2420
|
+
* const record = {
|
|
2421
|
+
* id: 1,
|
|
2422
|
+
* canRead: true,
|
|
2423
|
+
* canWrite: true,
|
|
2424
|
+
* };
|
|
2425
|
+
*
|
|
2426
|
+
* omitPrefixed(record, 'can'); // { id: 1 }
|
|
2427
|
+
*
|
|
2428
|
+
* @group Object
|
|
2429
|
+
*/
|
|
2430
|
+
declare function omitPrefixed(obj: Record<string, unknown>, prefix: string): Record<string, unknown>;
|
|
2431
|
+
|
|
2432
|
+
/**
|
|
2433
|
+
* Creates a new object composed of the picked object properties.
|
|
2434
|
+
*
|
|
2435
|
+
* This function takes an object and an array of keys, and returns a new object that
|
|
2436
|
+
* includes only the properties corresponding to the specified keys.
|
|
2437
|
+
*
|
|
2438
|
+
* @template T - The type of object.
|
|
2439
|
+
* @template K - The type of keys in object.
|
|
2440
|
+
* @param {T} obj - The object to pick keys from.
|
|
2441
|
+
* @param {K[]} keys - An array of keys to be picked from the object.
|
|
2442
|
+
* @returns {Pick<T, K>} A new object with the specified keys picked.
|
|
2443
|
+
*
|
|
2444
|
+
* @example
|
|
2445
|
+
* const obj = { a: 1, b: 2, c: 3 };
|
|
2446
|
+
* const result = pick(obj, ['a', 'c']);
|
|
2447
|
+
* // result will be { a: 1, c: 3 }
|
|
2448
|
+
*
|
|
2449
|
+
* @group Object
|
|
2450
|
+
*/
|
|
2451
|
+
declare function pick<T extends Record<string, any>, U extends keyof T>(obj: T | null | undefined, keys: Readonly<Array<U> | Set<U> | Array<string> | Set<string>>): Pick<T, U>;
|
|
2452
|
+
|
|
2453
|
+
interface PrefixedValuesOptions {
|
|
2454
|
+
/**
|
|
2455
|
+
* Key prefix
|
|
2456
|
+
*/
|
|
2457
|
+
prefix: string;
|
|
2458
|
+
/**
|
|
2459
|
+
* Remove prefix from resulted object
|
|
2460
|
+
* @default false
|
|
2461
|
+
*/
|
|
2462
|
+
prefixTrim?: boolean;
|
|
2463
|
+
}
|
|
2464
|
+
/**
|
|
2465
|
+
* Pick prefixed keys in target object
|
|
2466
|
+
*
|
|
2467
|
+
* @example
|
|
2468
|
+
* const record = {
|
|
2469
|
+
* id: 1,
|
|
2470
|
+
* canRead: true,
|
|
2471
|
+
* canWrite: true,
|
|
2472
|
+
* };
|
|
2473
|
+
*
|
|
2474
|
+
* // { canRead: true, canWrite: true }
|
|
2475
|
+
* pickPrefixed(record, 'can');
|
|
2476
|
+
*
|
|
2477
|
+
* // { Read: true, Write: true }
|
|
2478
|
+
* pickPrefixed(record, { prefix: 'can', prefixTrim: true });
|
|
2479
|
+
*
|
|
2480
|
+
* @group Object
|
|
2481
|
+
*/
|
|
2482
|
+
declare function pickPrefixed(obj: object, options: PrefixedValuesOptions | string): {};
|
|
2483
|
+
|
|
2484
|
+
/**
|
|
2485
|
+
* Same as `get` but for setting property by dot notation.
|
|
2486
|
+
*
|
|
2487
|
+
* @group Object
|
|
2488
|
+
*/
|
|
2489
|
+
declare const set: {
|
|
2490
|
+
<T extends object>(object: T, path: lodash.PropertyPath, value: any): T;
|
|
2491
|
+
<TResult>(object: object, path: lodash.PropertyPath, value: any): TResult;
|
|
2492
|
+
};
|
|
2493
|
+
|
|
2494
|
+
/**
|
|
2495
|
+
* Converts object into Map
|
|
2496
|
+
*
|
|
2497
|
+
* @example
|
|
2498
|
+
* const map = toMap({ user1: 'Andrew', user2: 'John' });
|
|
2499
|
+
*
|
|
2500
|
+
* map.get('user2'); // John
|
|
2501
|
+
*
|
|
2502
|
+
* @group Object
|
|
2503
|
+
*/
|
|
2504
|
+
declare const toMap: <T extends object>(obj: T) => Map<keyof T, T[keyof T]>;
|
|
2505
|
+
|
|
2506
|
+
/**
|
|
2507
|
+
* Converts a flattened object back into a nested structure.
|
|
2508
|
+
*
|
|
2509
|
+
* Takes an object with dot-separated keys and converts it into a nested object,
|
|
2510
|
+
* where each dot-separated part of the key represents a deeper level in the object.
|
|
2511
|
+
*
|
|
2512
|
+
* @param {Object} obj - The object to unflatten.
|
|
2513
|
+
* @param {string} [separator='_'] - The separator used to split the keys into their nested form. Defaults to '_'.
|
|
2514
|
+
* @returns {Object} The unflattened object, with nested keys restored to their original structure.
|
|
2515
|
+
*
|
|
2516
|
+
* @example
|
|
2517
|
+
* const obj = {
|
|
2518
|
+
* 'name': 'Andrew',
|
|
2519
|
+
* 'config_canReadPost': true,
|
|
2520
|
+
* 'config_canUpdatePost': true,
|
|
2521
|
+
* };
|
|
2522
|
+
*
|
|
2523
|
+
* unflatten(obj);
|
|
2524
|
+
* // Returns:
|
|
2525
|
+
* // {
|
|
2526
|
+
* // name: 'Andrew',
|
|
2527
|
+
* // config: {
|
|
2528
|
+
* // canReadPost: true,
|
|
2529
|
+
* // canUpdatePost: true
|
|
2530
|
+
* // },
|
|
2531
|
+
* // }
|
|
2532
|
+
*
|
|
2533
|
+
* @example
|
|
2534
|
+
* const flattenedObj = {
|
|
2535
|
+
* 'user.firstName': 'John',
|
|
2536
|
+
* 'user.lastName': 'Doe',
|
|
2537
|
+
* 'address.city': 'New York'
|
|
2538
|
+
* };
|
|
2539
|
+
*
|
|
2540
|
+
* unflatten(flattenedObj, '.');
|
|
2541
|
+
* // Returns:
|
|
2542
|
+
* // {
|
|
2543
|
+
* // user: {
|
|
2544
|
+
* // firstName: 'John',
|
|
2545
|
+
* // lastName: 'Doe'
|
|
2546
|
+
* // },
|
|
2547
|
+
* // address: {
|
|
2548
|
+
* // city: 'New York'
|
|
2549
|
+
* // }
|
|
2550
|
+
* // }
|
|
2551
|
+
*
|
|
2552
|
+
* @group Object
|
|
2553
|
+
*/
|
|
2554
|
+
declare function unflatten(obj: object, separator?: string): {};
|
|
2555
|
+
|
|
2556
|
+
/**
|
|
2557
|
+
* Same as `set` but unset by dot notation
|
|
2558
|
+
* @group Object
|
|
2559
|
+
*/
|
|
2560
|
+
declare const unset: (object: any, path: lodash.PropertyPath) => boolean;
|
|
2561
|
+
|
|
2562
|
+
/**
|
|
2563
|
+
* Asynchronously filters an array using an async predicate function.
|
|
2564
|
+
*
|
|
2565
|
+
* This function processes an array using an async function as the predicate,
|
|
2566
|
+
* allowing you to avoid blocking the event loop while iterating over large arrays.
|
|
2567
|
+
* It ensures that the iteration happens asynchronously with minimal impact on the event loop,
|
|
2568
|
+
* making it useful for processing large datasets or performing async operations on each element.
|
|
2569
|
+
*
|
|
2570
|
+
* @param array - The array to be filtered.
|
|
2571
|
+
* @param predicate - The async predicate function.
|
|
2572
|
+
* It takes three arguments: the current value, the index of the current value, and the full array.
|
|
2573
|
+
* It should return a boolean value or a promise that resolves to a boolean indicating whether the value should be kept in the result array.
|
|
2574
|
+
*
|
|
2575
|
+
* @returns {Promise<T[]>} A promise that resolves to a new array containing the elements that satisfy the predicate.
|
|
2576
|
+
*
|
|
2577
|
+
* @example
|
|
2578
|
+
* const users = Array.from({ length: 100000 }).map((_, idx) => ({
|
|
2579
|
+
* id: idx,
|
|
2580
|
+
* name: 'User: ' + (idx + 1)
|
|
2581
|
+
* }));
|
|
2582
|
+
*
|
|
2583
|
+
* async function first100Users() {
|
|
2584
|
+
* return await asyncFilter(users, (user) => user.id < 100);
|
|
2585
|
+
* }
|
|
2586
|
+
*
|
|
2587
|
+
* Promise.all([
|
|
2588
|
+
* first100Users(),
|
|
2589
|
+
* otherUsefulTask(),
|
|
2590
|
+
* ]).then(console.log);
|
|
2591
|
+
*
|
|
2592
|
+
* @group Promise
|
|
2593
|
+
*/
|
|
2594
|
+
declare function asyncFilter<T>(array: T[], predicate: (value: T, index: number, array: Array<T>) => Promise<boolean> | boolean): Promise<T[]>;
|
|
2595
|
+
|
|
2596
|
+
/**
|
|
2597
|
+
* Asynchronously finds the first element in an array that satisfies the provided async predicate.
|
|
2598
|
+
*
|
|
2599
|
+
* This function iterates through an array and applies an asynchronous predicate to each element.
|
|
2600
|
+
* If the predicate resolves to a truthy value for any element, that element is returned immediately.
|
|
2601
|
+
* The function is designed to prevent blocking the event loop during iteration, making it suitable
|
|
2602
|
+
* for processing large arrays without impacting performance.
|
|
2603
|
+
*
|
|
2604
|
+
* @param array - The array to search through.
|
|
2605
|
+
* @param callbackfn - The asynchronous predicate function.
|
|
2606
|
+
* It takes three arguments: the current value, the index of the current value, and the full array.
|
|
2607
|
+
* The predicate function should return a boolean or a promise that resolves to a boolean indicating
|
|
2608
|
+
* whether the current value satisfies the condition.
|
|
2609
|
+
*
|
|
2610
|
+
* @returns {Promise<T | undefined>} A promise that resolves to the first element that satisfies the predicate, or `undefined` if no element matches.
|
|
2611
|
+
*
|
|
2612
|
+
* @example
|
|
2613
|
+
* // Example of using asyncFind to find users by ID asynchronously
|
|
2614
|
+
* const users = Array.from({ length: 100000 }).map((_, idx) => ({
|
|
2615
|
+
* id: idx,
|
|
2616
|
+
* name: 'User: ' + (idx + 1)
|
|
2617
|
+
* }));
|
|
2618
|
+
*
|
|
2619
|
+
* async function findById(userId: number) {
|
|
2620
|
+
* return await asyncFind(users, (user) => user.id === userId);
|
|
2621
|
+
* }
|
|
2622
|
+
*
|
|
2623
|
+
* Promise.all([
|
|
2624
|
+
* findById(5000),
|
|
2625
|
+
* findById(6000),
|
|
2626
|
+
* ]).then(console.log);
|
|
2627
|
+
*
|
|
2628
|
+
* @group Promise
|
|
2629
|
+
*/
|
|
2630
|
+
declare function asyncFind<T>(array: T[], callbackfn: (value: T, index: number, array: T[]) => Promise<unknown> | unknown): Promise<T | undefined>;
|
|
2631
|
+
|
|
2632
|
+
/**
|
|
2633
|
+
* Asynchronously iterates over an array, executing the provided callback for each element with support for parallel processing.
|
|
2634
|
+
*
|
|
2635
|
+
* This function is similar to `Array.prototype.forEach()`, but it allows asynchronous operations in parallel for each array element.
|
|
2636
|
+
* It also prevents blocking the event loop while iterating through large arrays, improving performance for heavy tasks.
|
|
2637
|
+
* The function processes items in batches to manage concurrency and can be configured to process multiple items at the same time.
|
|
2638
|
+
*
|
|
2639
|
+
* **Note**: The callback function can return either a promise or a value. If it returns a promise, `asyncForEach` will wait for it to resolve before moving to the next iteration.
|
|
2640
|
+
*
|
|
2641
|
+
* @param array - The array to iterate over.
|
|
2642
|
+
* @param callbackfn - The async callback function to execute for each element.
|
|
2643
|
+
* This function takes three parameters:
|
|
2644
|
+
* - `value`: The current element of the array.
|
|
2645
|
+
* - `index`: The index of the current element in the array.
|
|
2646
|
+
* - `array`: The array that is being iterated over.
|
|
2647
|
+
* The function should either return a `void` or a `Promise` that resolves when the async operation is done.
|
|
2648
|
+
*
|
|
2649
|
+
* @param {Object} [options] - Optional settings to control the concurrency of the operation.
|
|
2650
|
+
* @param {number} [options.concurrency=1] - The number of items to process in parallel. Defaults to 1 (sequential processing).
|
|
2651
|
+
*
|
|
2652
|
+
* @returns {Promise<void>} A promise that resolves when all elements have been processed.
|
|
2653
|
+
*
|
|
2654
|
+
* @example
|
|
2655
|
+
* async function task(taskName: string) {
|
|
2656
|
+
* const largeArray = Array.from({ length: 100000 }).map((_, idx) => idx);
|
|
2657
|
+
*
|
|
2658
|
+
* await asyncForEach(largeArray, (value) => {
|
|
2659
|
+
* if (value % 100 === 0) {
|
|
2660
|
+
* console.log(taskName, 'handle:', value);
|
|
2661
|
+
* }
|
|
2662
|
+
* });
|
|
2663
|
+
* }
|
|
2664
|
+
*
|
|
2665
|
+
* Promise.all([
|
|
2666
|
+
* task('task 1'),
|
|
2667
|
+
* task('task 2'),
|
|
2668
|
+
* ]);
|
|
2669
|
+
*
|
|
2670
|
+
* @group Promise
|
|
2671
|
+
*/
|
|
2672
|
+
declare function asyncForEach<T>(array: T[], callbackfn: (value: T, index: number, array: Array<T>) => Promise<void> | void, { concurrency }?: {
|
|
2673
|
+
concurrency?: number | undefined;
|
|
2674
|
+
}): Promise<void>;
|
|
2675
|
+
|
|
2676
|
+
/**
|
|
2677
|
+
* An asynchronous queue implementation that can be iterated using an async iterator.
|
|
2678
|
+
* It allows items to be added (`put`) and consumed asynchronously, with the ability to signal when the queue is closed.
|
|
2679
|
+
* This class supports async iteration, enabling users to process items as they become available, and provides an end signal once the queue is closed.
|
|
2680
|
+
*
|
|
2681
|
+
* @example
|
|
2682
|
+
* const textStream = new AsyncIterableQueue<string>();
|
|
2683
|
+
*
|
|
2684
|
+
* const readTimer = setInterval(() => {
|
|
2685
|
+
* textStream.put('Hey ' + Math.random());
|
|
2686
|
+
* }, 100);
|
|
2687
|
+
*
|
|
2688
|
+
* setTimeout(() => {
|
|
2689
|
+
* textStream.close();
|
|
2690
|
+
* clearInterval(readTimer);
|
|
2691
|
+
* });
|
|
2692
|
+
*
|
|
2693
|
+
* for await (const text of textStream) {
|
|
2694
|
+
* console.log('text part', { text });
|
|
2695
|
+
* }
|
|
2696
|
+
*
|
|
2697
|
+
* @group Promise
|
|
2698
|
+
*/
|
|
2699
|
+
declare class AsyncIterableQueue<T> implements AsyncIterable<T> {
|
|
2700
|
+
private _queue;
|
|
2701
|
+
private _closed;
|
|
2702
|
+
private static readonly QUEUE_END_MARKER;
|
|
2703
|
+
constructor();
|
|
2704
|
+
get closed(): boolean;
|
|
2705
|
+
put(item: T): void;
|
|
2706
|
+
close(): void;
|
|
2707
|
+
[Symbol.asyncIterator](): AsyncIterator<T>;
|
|
2708
|
+
}
|
|
2709
|
+
|
|
2710
|
+
/**
|
|
2711
|
+
* Asynchronously maps over an array, applying the provided callback function to each element,
|
|
2712
|
+
* with support for parallel processing of array elements.
|
|
2713
|
+
*
|
|
2714
|
+
* This function is similar to `arr.map()`, but allows asynchronous operations
|
|
2715
|
+
* for each array element, helping to avoid blocking the event loop when processing large arrays.
|
|
2716
|
+
* It processes the array elements in batches, providing support for concurrency, meaning multiple
|
|
2717
|
+
* elements can be processed in parallel.
|
|
2718
|
+
*
|
|
2719
|
+
* **Note**: The callback function can return either a value or a `Promise`. If a `Promise` is returned,
|
|
2720
|
+
* `asyncMap` will wait for it to resolve before moving on to the next iteration.
|
|
2721
|
+
*
|
|
2722
|
+
* @param array - The array to iterate over.
|
|
2723
|
+
* @param callbackfn - The async callback function to apply to each element.
|
|
2724
|
+
* This function takes three parameters:
|
|
2725
|
+
* - `value`: The current element of the array.
|
|
2726
|
+
* - `index`: The index of the current element in the array.
|
|
2727
|
+
* - `array`: The array being processed.
|
|
2728
|
+
* The callback should return either a transformed value (`U`) or a `Promise<U>`.
|
|
2729
|
+
*
|
|
2730
|
+
* @param {Object} [options] - Optional configuration for controlling concurrency.
|
|
2731
|
+
* @param {number} [options.concurrency=1] - The number of items to process concurrently. Default is 1 (sequential processing).
|
|
2732
|
+
*
|
|
2733
|
+
* @returns {Promise<U[]>} A promise that resolves to an array of transformed elements.
|
|
2734
|
+
*
|
|
2735
|
+
* @example
|
|
2736
|
+
* const users = Array.from({ length: 100 }).map((_, idx) => ({
|
|
2737
|
+
* id: idx,
|
|
2738
|
+
* name: 'User: ' + (idx + 1)
|
|
2739
|
+
* }));
|
|
2740
|
+
*
|
|
2741
|
+
* async function withUserClients() {
|
|
2742
|
+
* return await asyncMap(users, async (user) => {
|
|
2743
|
+
* const clients = await db.clients.find({ user: user.id });
|
|
2744
|
+
*
|
|
2745
|
+
* return { ...user, clients };
|
|
2746
|
+
* }, { concurrency: 10 });
|
|
2747
|
+
* }
|
|
2748
|
+
*
|
|
2749
|
+
* Promise.all([
|
|
2750
|
+
* withUserClients(),
|
|
2751
|
+
* otherUsefulTask(),
|
|
2752
|
+
* ]).then(console.log);
|
|
2753
|
+
*
|
|
2754
|
+
* @group Promise
|
|
2755
|
+
*/
|
|
2756
|
+
declare function asyncMap<T, U>(array: T[], callbackfn: (value: T, index: number, array: Array<T>) => Promise<U> | U, { concurrency }?: {
|
|
2757
|
+
concurrency?: number | undefined;
|
|
2758
|
+
}): Promise<Array<U>>;
|
|
2759
|
+
|
|
2760
|
+
/**
|
|
2761
|
+
* A custom promise that supports cancellation.
|
|
2762
|
+
* Allows users to cancel the promise operation before it completes, avoiding unnecessary execution.
|
|
2763
|
+
* This class provides a mechanism to perform asynchronous tasks that can be stopped midway by calling the `cancel` method.
|
|
2764
|
+
*
|
|
2765
|
+
* @example
|
|
2766
|
+
* const task = new CancellablePromise<void>(async (resolve, reject, onCancel) => {
|
|
2767
|
+
* let cancelled = false;
|
|
2768
|
+
* onCancel(() => {
|
|
2769
|
+
* cancelled = true; // Define the cancellation logic here
|
|
2770
|
+
* });
|
|
2771
|
+
*
|
|
2772
|
+
* while (!cancelled) {
|
|
2773
|
+
* await delay(1000); // Simulate async work
|
|
2774
|
+
* console.log('handling task...');
|
|
2775
|
+
* }
|
|
2776
|
+
* });
|
|
2777
|
+
*
|
|
2778
|
+
* // Cancel the task after 5 seconds
|
|
2779
|
+
* setTimeout(() => task.cancel(), 5000);
|
|
2780
|
+
*
|
|
2781
|
+
* await task; // This will be cancelled before it completes
|
|
2782
|
+
* console.log('Task completed or cancelled');
|
|
2783
|
+
*
|
|
2784
|
+
* @group Promise
|
|
2785
|
+
*/
|
|
2786
|
+
declare class CancellablePromise<T> implements Promise<T> {
|
|
2787
|
+
#private;
|
|
2788
|
+
constructor(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void, onCancel: (cancelFn: () => void) => void) => void);
|
|
2789
|
+
get [Symbol.toStringTag](): string;
|
|
2790
|
+
get isCancelled(): boolean;
|
|
2791
|
+
get error(): Error | null;
|
|
2792
|
+
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | Promise<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | Promise<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
2793
|
+
catch<TResult = never>(onrejected?: ((reason: any) => TResult | Promise<TResult>) | null): Promise<T | TResult>;
|
|
2794
|
+
finally(onfinally?: (() => void) | null): Promise<T>;
|
|
2795
|
+
cancel(): void;
|
|
2796
|
+
static from<T>(promise: Promise<T>): CancellablePromise<T>;
|
|
2797
|
+
}
|
|
2798
|
+
|
|
2799
|
+
interface Defer<T = unknown> {
|
|
2800
|
+
promise: Promise<T>;
|
|
2801
|
+
resolve: (value: T) => void;
|
|
2802
|
+
reject: (value: any) => void;
|
|
2803
|
+
}
|
|
2804
|
+
/**
|
|
2805
|
+
* Old known defer :)
|
|
2806
|
+
*
|
|
2807
|
+
* @example
|
|
2808
|
+
* function loadModule() {
|
|
2809
|
+
* const q = defer<void>();
|
|
2810
|
+
*
|
|
2811
|
+
* setTimeout(() => q.resolve(), 5000);
|
|
2812
|
+
*
|
|
2813
|
+
* return q.promise;
|
|
2814
|
+
* }
|
|
2815
|
+
*
|
|
2816
|
+
* await loadModule();
|
|
2817
|
+
*
|
|
2818
|
+
* @group Promise
|
|
2819
|
+
*/
|
|
2820
|
+
declare function defer<T = void>(): Defer<T>;
|
|
2821
|
+
|
|
2822
|
+
/**
|
|
2823
|
+
* Returns a promise that resolves after the provided delay.
|
|
2824
|
+
*
|
|
2825
|
+
* If the delay is specified as `'tick'`, the promise resolves after the next event loop tick.
|
|
2826
|
+
*
|
|
2827
|
+
* If a numeric delay is provided, the promise resolves after the specified time in milliseconds.
|
|
2828
|
+
*
|
|
2829
|
+
* This is useful for introducing delays in asynchronous code, such as for throttling or rate-limiting,
|
|
2830
|
+
* or simply pausing execution between iterations.
|
|
2831
|
+
*
|
|
2832
|
+
* @param amount - The delay duration in milliseconds, or `'tick'` for a resolution after the next event loop tick.
|
|
2833
|
+
* @returns A promise that resolves after the specified delay.
|
|
2834
|
+
*
|
|
2835
|
+
* @example
|
|
2836
|
+
* let seconds = 0;
|
|
2837
|
+
*
|
|
2838
|
+
* // This will print numbers 1, 2, 3... every second
|
|
2839
|
+
* while (true) {
|
|
2840
|
+
* await delay(1000);
|
|
2841
|
+
* console.log(++seconds);
|
|
2842
|
+
* }
|
|
2843
|
+
*
|
|
2844
|
+
* @example
|
|
2845
|
+
* // This will wait until the next event loop tick before resolving
|
|
2846
|
+
* await delay('tick');
|
|
2847
|
+
*
|
|
2848
|
+
* @group Promise
|
|
2849
|
+
*/
|
|
2850
|
+
declare function delay(amount?: 'tick' | number): Promise<void>;
|
|
2851
|
+
|
|
2852
|
+
/**
|
|
2853
|
+
* Executes the provided callback as soon as the event loop is idle.
|
|
2854
|
+
* This function allows you to run tasks at the earliest available opportunity
|
|
2855
|
+
* without blocking the main execution flow, making it ideal for tasks that can
|
|
2856
|
+
* be deferred until the browser is idle or the process is idle.
|
|
2857
|
+
*
|
|
2858
|
+
* It uses `requestIdleCallback` if available, otherwise it falls back to
|
|
2859
|
+
* `requestAnimationFrame`, `process.nextTick`, or `setTimeout` depending on the environment.
|
|
2860
|
+
*
|
|
2861
|
+
* @example
|
|
2862
|
+
* fastIdle(() => {
|
|
2863
|
+
* console.log('1');
|
|
2864
|
+
* });
|
|
2865
|
+
*
|
|
2866
|
+
* console.log('2');
|
|
2867
|
+
*
|
|
2868
|
+
* // Output:
|
|
2869
|
+
* // 2
|
|
2870
|
+
* // 1
|
|
2871
|
+
*
|
|
2872
|
+
* @param callback - The callback function to be executed when the event loop is idle.
|
|
2873
|
+
*
|
|
2874
|
+
* @group Promise
|
|
2875
|
+
*/
|
|
2876
|
+
declare function fastIdle(callback: Fn): void;
|
|
2877
|
+
/**
|
|
2878
|
+
* Same as `fastIdle` but promisified
|
|
2879
|
+
*
|
|
2880
|
+
* @example
|
|
2881
|
+
* fastIdlePromise().then(() => {
|
|
2882
|
+
* console.log('1');
|
|
2883
|
+
* });
|
|
2884
|
+
*
|
|
2885
|
+
* console.log('2');
|
|
2886
|
+
*
|
|
2887
|
+
* // 2
|
|
2888
|
+
* // 1
|
|
2889
|
+
*
|
|
2890
|
+
* @group Promise
|
|
2891
|
+
*/
|
|
2892
|
+
declare function fastIdlePromise(): Promise<void>;
|
|
2893
|
+
|
|
2894
|
+
type NoneToVoidFunction = () => void;
|
|
2895
|
+
/**
|
|
2896
|
+
* Stacks callbacks for `requestAnimationFrame` into a single execution call.
|
|
2897
|
+
*
|
|
2898
|
+
* This function allows multiple `fastRaf` calls to be batched into a single animation frame callback.
|
|
2899
|
+
* The callbacks are executed in the same frame, one after the other. Additionally, if `withTimeoutFallback` is true,
|
|
2900
|
+
* the callbacks will be executed after a fallback timeout if `requestAnimationFrame` is not available.
|
|
2901
|
+
* If called from within another RAF callback, the execution might be immediate.
|
|
2902
|
+
*
|
|
2903
|
+
* @example
|
|
2904
|
+
* // Callbacks will be executed in the same `requestAnimationFrame` cycle
|
|
2905
|
+
* fastRaf(() => console.log(1));
|
|
2906
|
+
* fastRaf(() => console.log(2));
|
|
2907
|
+
*
|
|
2908
|
+
* // Output:
|
|
2909
|
+
* // 1
|
|
2910
|
+
* // 2
|
|
2911
|
+
*
|
|
2912
|
+
* @param callback The callback function to be executed in the next `requestAnimationFrame`.
|
|
2913
|
+
* @param [withTimeoutFallback=false] Optional flag to execute callbacks after a fallback timeout if `requestAnimationFrame` is not available.
|
|
2914
|
+
* @group Promise
|
|
2915
|
+
*/
|
|
2916
|
+
declare function fastRaf(callback: NoneToVoidFunction, withTimeoutFallback?: boolean): void;
|
|
2917
|
+
declare function rafPromise(): Promise<void>;
|
|
2918
|
+
|
|
2919
|
+
/**
|
|
2920
|
+
* Creates a cooldown function that resolves after a specified number of executions (`amount`).
|
|
2921
|
+
* The cooldown can either occur on the `next` tick or after a specified delay.
|
|
2922
|
+
*
|
|
2923
|
+
* This is useful for controlling the rate of asynchronous operations, allowing you to pause
|
|
2924
|
+
* for a specified amount of time after a certain number of iterations in a loop.
|
|
2925
|
+
*
|
|
2926
|
+
* @example
|
|
2927
|
+
* // Create a cooldown function that waits 1 tick for every 10th execution
|
|
2928
|
+
* const cooldown = nextTickIteration(10);
|
|
2929
|
+
*
|
|
2930
|
+
* for (const item of array) {
|
|
2931
|
+
* await cooldown(); // Wait 1 tick for every 10th call
|
|
2932
|
+
* // Perform some async operation here
|
|
2933
|
+
* }
|
|
2934
|
+
*
|
|
2935
|
+
* @example
|
|
2936
|
+
* // Create a cooldown function with a 100ms delay after every 5 executions
|
|
2937
|
+
* const cooldownWithDelay = nextTickIteration(5, 100);
|
|
2938
|
+
* for (const item of array) {
|
|
2939
|
+
* await cooldownWithDelay(); // Wait 100ms after every 5th call
|
|
2940
|
+
* // Perform some async operation here
|
|
2941
|
+
* }
|
|
2942
|
+
*
|
|
2943
|
+
* @param amount The number of executions after which the cooldown should occur.
|
|
2944
|
+
* @param delay The delay type or amount. If 'tick', it uses the next idle tick.
|
|
2945
|
+
* If a number is provided, it specifies a delay in milliseconds.
|
|
2946
|
+
* @returns A function that, when called, returns a promise resolving after the specified cooldown period.
|
|
2947
|
+
*
|
|
2948
|
+
* @group Promise
|
|
2949
|
+
*/
|
|
2950
|
+
declare function nextTickIteration(amount: number, delay?: number | 'tick'): () => Promise<void>;
|
|
2951
|
+
|
|
2952
|
+
/**
|
|
2953
|
+
* A basic queue implementation with a limit and event-based synchronization.
|
|
2954
|
+
*
|
|
2955
|
+
* This class allows you to put items into a queue and retrieve them asynchronously.
|
|
2956
|
+
* If the queue exceeds a specified limit, the `put` operation will wait until an item is retrieved,
|
|
2957
|
+
* and similarly, the `get` operation will wait if there are no items available in the queue.
|
|
2958
|
+
*
|
|
2959
|
+
* @example
|
|
2960
|
+
* // Create a queue with a limit of 10 items
|
|
2961
|
+
* const sendQueue = new Queue<any>(10);
|
|
2962
|
+
*
|
|
2963
|
+
* // Add items to the queue
|
|
2964
|
+
* sendQueue.put({ url: '/api/message.send', params: { text: 'hello' } });
|
|
2965
|
+
* sendQueue.put({ url: '/api/message.send', params: { text: 'how are you?' } });
|
|
2966
|
+
*
|
|
2967
|
+
* // Retrieve and process items from the queue asynchronously
|
|
2968
|
+
* while (true) {
|
|
2969
|
+
* const req = await sendQueue.get();
|
|
2970
|
+
* http.post(req.url, { body: req.params });
|
|
2971
|
+
* }
|
|
2972
|
+
*
|
|
2973
|
+
* @param limit - Optional maximum number of items the queue can hold. If not provided, the queue has no limit.
|
|
2974
|
+
*
|
|
2975
|
+
* @group Promise
|
|
2976
|
+
*/
|
|
2977
|
+
declare class Queue<T> {
|
|
2978
|
+
#private;
|
|
2979
|
+
items: T[];
|
|
2980
|
+
constructor(limit?: number);
|
|
2981
|
+
get(): Promise<T>;
|
|
2982
|
+
put(item: T): Promise<void>;
|
|
2983
|
+
}
|
|
2984
|
+
|
|
2985
|
+
type SimpleEventMap<T> = Record<keyof T, any[]> | SimpleDefaultEventMap;
|
|
2986
|
+
type SimpleDefaultEventMap = [never];
|
|
2987
|
+
type Key<K, T> = T extends SimpleDefaultEventMap ? string | symbol : K | keyof T;
|
|
2988
|
+
type Listener<K, T, F> = T extends SimpleDefaultEventMap ? F : K extends keyof T ? T[K] extends unknown[] ? (...args: T[K]) => void : never : never;
|
|
2989
|
+
type Listener1<K, T> = Listener<K, T, (...args: any[]) => void>;
|
|
2990
|
+
type Args<K, T> = T extends SimpleDefaultEventMap ? [...args: any[]] : K extends keyof T ? T[K] : never;
|
|
2991
|
+
/**
|
|
2992
|
+
* Simplified version on nodejs `EventEmitter` but platform agnostic
|
|
2993
|
+
*
|
|
2994
|
+
* @example
|
|
2995
|
+
* const emitter = new SimpleEventEmitter();
|
|
2996
|
+
*
|
|
2997
|
+
* emitter.on('message', (data) => {
|
|
2998
|
+
* console.log('msg', data)
|
|
2999
|
+
* });
|
|
3000
|
+
*
|
|
3001
|
+
* emitter.once('message', (data) => {
|
|
3002
|
+
* console.log('once msg', data)
|
|
3003
|
+
* });
|
|
3004
|
+
*
|
|
3005
|
+
* emitter.emit('message', { text: 'Hello' });
|
|
3006
|
+
* emitter.emit('message', { text: 'Hello 2' });
|
|
3007
|
+
*
|
|
3008
|
+
* @group Promise
|
|
3009
|
+
*/
|
|
3010
|
+
declare class SimpleEventEmitter<T extends SimpleEventMap<T> = SimpleDefaultEventMap> {
|
|
3011
|
+
#private;
|
|
3012
|
+
constructor();
|
|
3013
|
+
static once(emitter: SimpleEventEmitter, eventName: string | symbol): Promise<any[]>;
|
|
3014
|
+
emit<K>(eventName: Key<K, T>, ...args: Args<K, T>): boolean;
|
|
3015
|
+
on<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
|
3016
|
+
once<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
|
3017
|
+
off<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
|
3018
|
+
removeAllListeners(eventName?: Key<unknown, T>): this;
|
|
3019
|
+
}
|
|
3020
|
+
|
|
3021
|
+
/**
|
|
3022
|
+
* Throws an error if the provided promise or callback is not resolved within the specified timeout period.
|
|
3023
|
+
*
|
|
3024
|
+
* This function can be used to ensure that an asynchronous operation does not take too long to complete.
|
|
3025
|
+
* If the operation exceeds the specified time limit, the provided `timeoutError` is thrown.
|
|
3026
|
+
*
|
|
3027
|
+
* @example
|
|
3028
|
+
* // Example usage: Throw an error if no response is received within 1 second
|
|
3029
|
+
* await timeout(
|
|
3030
|
+
* 1000, // Timeout duration in milliseconds
|
|
3031
|
+
* (signal) => {
|
|
3032
|
+
* const account = await http.get('/api/users/me');
|
|
3033
|
+
*
|
|
3034
|
+
* if (signal.aborted) return; // If the timeout occurs, abort the operation
|
|
3035
|
+
*
|
|
3036
|
+
* const statistics = await http.get('/api/users/me/statistics');
|
|
3037
|
+
*
|
|
3038
|
+
* return { ...account, statistics };
|
|
3039
|
+
* },
|
|
3040
|
+
* new Error('Request account timeout') // Custom error to throw on timeout
|
|
3041
|
+
* );
|
|
3042
|
+
*
|
|
3043
|
+
* @param ms - The maximum time (in milliseconds) to wait for the promise or callback to resolve.
|
|
3044
|
+
* @param promiseOrCallback - The asynchronous operation to execute. This can either be:
|
|
3045
|
+
* - A `Promise` that will be awaited until completion, or
|
|
3046
|
+
* - A function that takes an `AbortSignal` and returns a `Promise` or a value.
|
|
3047
|
+
* @param timeoutError - The error that will be thrown if the timeout is reached before the promise or callback resolves.
|
|
3048
|
+
* (Defaults to `Error('Timeout')` if not provided).
|
|
3049
|
+
* @returns A `Promise` that resolves with the result of the provided `promiseOrCallback`, or rejects with the `timeoutError` if the timeout occurs.
|
|
3050
|
+
*
|
|
3051
|
+
* @throws {Error} - Throws the `timeoutError` if the operation exceeds the specified timeout.
|
|
3052
|
+
*
|
|
3053
|
+
* @group Promise
|
|
3054
|
+
*/
|
|
3055
|
+
declare function timeout<T = any>(ms: number, promiseOrCallback: Promise<T> | ((abortSignal: AbortSignal) => Awaitable<T>), timeoutError?: any): Promise<T>;
|
|
3056
|
+
|
|
3057
|
+
type TypeOf = keyof TypeOfMap;
|
|
3058
|
+
type TypeOfMap = {
|
|
3059
|
+
null: null;
|
|
3060
|
+
undefined: undefined;
|
|
3061
|
+
object: Record<PropertyKey, any>;
|
|
3062
|
+
string: string;
|
|
3063
|
+
number: number;
|
|
3064
|
+
function: AnyFunction;
|
|
3065
|
+
bigint: bigint;
|
|
3066
|
+
boolean: boolean;
|
|
3067
|
+
symbol: symbol;
|
|
3068
|
+
date: Date;
|
|
3069
|
+
array: any[];
|
|
3070
|
+
map: Map<any, any>;
|
|
3071
|
+
weakmap: WeakMap<WeakKey, any>;
|
|
3072
|
+
set: Set<any>;
|
|
3073
|
+
weakset: WeakSet<WeakKey>;
|
|
3074
|
+
unknown: unknown;
|
|
3075
|
+
};
|
|
3076
|
+
/**
|
|
3077
|
+
* Typeof that you deserve
|
|
3078
|
+
* @group Utility Functions
|
|
3079
|
+
*/
|
|
3080
|
+
declare function typeOf(value: unknown): TypeOf;
|
|
3081
|
+
|
|
3082
|
+
type StringifyOptions = {
|
|
3083
|
+
/**
|
|
3084
|
+
* Exclude empty values, checking by `isEmpty`
|
|
3085
|
+
* @default true
|
|
3086
|
+
*/
|
|
3087
|
+
excludeEmpty?: boolean;
|
|
3088
|
+
/**
|
|
3089
|
+
* Exclude values when equals with defaults
|
|
3090
|
+
*/
|
|
3091
|
+
excludeDefaults?: Record<string, any>;
|
|
3092
|
+
};
|
|
3093
|
+
/**
|
|
3094
|
+
* Simple query stringy interface that supports encoding/decoding of `Array`, `Set`, `Map`, `Object`, `BigInt`
|
|
3095
|
+
*
|
|
3096
|
+
* @example
|
|
3097
|
+
* // encode
|
|
3098
|
+
* qs.stringify({ page: 1, limit: 10 }); // 'page=1&limit=10'
|
|
3099
|
+
*
|
|
3100
|
+
* // decode
|
|
3101
|
+
* const defaults = { page: 1, limit: 10 };
|
|
3102
|
+
* const params = qs.parse('page=5&limit=abc', defaults); // { page: 5, limit: 10 }
|
|
3103
|
+
*
|
|
3104
|
+
* @group Utility Functions
|
|
3105
|
+
*/
|
|
3106
|
+
declare const qs: {
|
|
3107
|
+
toParams: typeof toParams;
|
|
3108
|
+
stringify: typeof stringify;
|
|
3109
|
+
stringifyValue: typeof stringifyValue;
|
|
3110
|
+
parse: typeof parse;
|
|
3111
|
+
parseValue: typeof parseValue;
|
|
3112
|
+
merge: typeof merge;
|
|
3113
|
+
};
|
|
3114
|
+
/**
|
|
3115
|
+
* Merge first level values
|
|
3116
|
+
*/
|
|
3117
|
+
declare function merge(...values: Record<string, any>[]): Record<string, any>;
|
|
3118
|
+
/**
|
|
3119
|
+
* Simple function to transform object into query string (not standards)
|
|
3120
|
+
*/
|
|
3121
|
+
declare function stringify(obj: Record<string, any>, options?: StringifyOptions): string;
|
|
3122
|
+
/**
|
|
3123
|
+
* Prepare search params object
|
|
3124
|
+
*/
|
|
3125
|
+
declare function toParams(obj: Record<string, any>, options?: StringifyOptions): Record<string, string>;
|
|
3126
|
+
/**
|
|
3127
|
+
* Parse query string as is without type casting
|
|
3128
|
+
*/
|
|
3129
|
+
declare function parse(value: string): Record<string, string>;
|
|
3130
|
+
/**
|
|
3131
|
+
* Parse query string and use default object as type cast schema
|
|
3132
|
+
*/
|
|
3133
|
+
declare function parse<T extends Record<string, any>>(value: string, defaults: Partial<T>): T;
|
|
3134
|
+
/**
|
|
3135
|
+
* Parse query params and use default object as type cast schema
|
|
3136
|
+
*/
|
|
3137
|
+
declare function parse<T extends Record<string, any>>(value: Record<string, any>, defaults: T): Partial<T>;
|
|
3138
|
+
/**
|
|
3139
|
+
* Stringify value to use as query parameter
|
|
3140
|
+
*/
|
|
3141
|
+
declare function stringifyValue(value: unknown): string;
|
|
3142
|
+
/**
|
|
3143
|
+
* Parse string query value as a type
|
|
3144
|
+
*/
|
|
3145
|
+
declare function parseValue<T extends TypeOf>(value: any, asType: T): TypeOfMap[T] | undefined;
|
|
3146
|
+
|
|
3147
|
+
type RetryOnErrorConfig = {
|
|
3148
|
+
/**
|
|
3149
|
+
* The function to execute before retry attempt; Allows to update parameters for the main function by returning then in an array
|
|
3150
|
+
*/
|
|
3151
|
+
beforeRetryCallback?: (attempt: number, lastAttempt: boolean) => Promise<unknown[] | void>;
|
|
3152
|
+
/**
|
|
3153
|
+
* Error validation function. If returns true, the main callback's considered ready to be executed again
|
|
3154
|
+
*/
|
|
3155
|
+
shouldRetryBasedOnError: (error: unknown, attempt: number) => boolean;
|
|
3156
|
+
/**
|
|
3157
|
+
* Number of retries until the execution fails
|
|
3158
|
+
*/
|
|
3159
|
+
maxRetriesNumber: number;
|
|
3160
|
+
/**
|
|
3161
|
+
* Delay multiply factor
|
|
3162
|
+
*/
|
|
3163
|
+
delayFactor?: number;
|
|
3164
|
+
/**
|
|
3165
|
+
* Delay min milliseconds
|
|
3166
|
+
*/
|
|
3167
|
+
delayMinMs?: number;
|
|
3168
|
+
/**
|
|
3169
|
+
* Delay max milliseconds
|
|
3170
|
+
*/
|
|
3171
|
+
delayMaxMs?: number;
|
|
3172
|
+
};
|
|
3173
|
+
/**
|
|
3174
|
+
* @example
|
|
3175
|
+
* await retryOnError({
|
|
3176
|
+
* maxRetriesNumber: 10,
|
|
3177
|
+
* delayFactor: 2,
|
|
3178
|
+
* delayMinMs: 1000,
|
|
3179
|
+
* delayMaxMs: 3000,
|
|
3180
|
+
* shouldRetryBasedOnError(error, attemptNumber) {
|
|
3181
|
+
* return error.code !== 'RECORD_EXISTS';
|
|
3182
|
+
* }
|
|
3183
|
+
* }, async () => {
|
|
3184
|
+
* await db.transactions.insert(doc);
|
|
3185
|
+
* });
|
|
3186
|
+
*
|
|
3187
|
+
* @group Errors
|
|
3188
|
+
*/
|
|
3189
|
+
declare function retryOnError<T extends AnyFunction>({ beforeRetryCallback, maxRetriesNumber, shouldRetryBasedOnError, delayFactor, delayMaxMs, delayMinMs, }: RetryOnErrorConfig, fn: T): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;
|
|
3190
|
+
|
|
3191
|
+
/**
|
|
3192
|
+
* Converts a string to camel case.
|
|
3193
|
+
*
|
|
3194
|
+
* Camel case is the naming convention in which the first word is written in lowercase and
|
|
3195
|
+
* each subsequent word begins with a capital letter, concatenated without any separator characters.
|
|
3196
|
+
*
|
|
3197
|
+
* @param {string} str - The string that is to be changed to camel case.
|
|
3198
|
+
* @returns {string} - The converted string to camel case.
|
|
3199
|
+
*
|
|
3200
|
+
* @example
|
|
3201
|
+
* const convertedStr1 = camelCase('camelCase') // returns 'camelCase'
|
|
3202
|
+
* const convertedStr2 = camelCase('some whitespace') // returns 'someWhitespace'
|
|
3203
|
+
* const convertedStr3 = camelCase('hyphen-text') // returns 'hyphenText'
|
|
3204
|
+
* const convertedStr4 = camelCase('HTTPRequest') // returns 'httpRequest'
|
|
3205
|
+
* const convertedStr5 = camelCase('Keep unicode 😅') // returns 'keepUnicode😅'
|
|
3206
|
+
*
|
|
3207
|
+
* @group Strings
|
|
3208
|
+
*/
|
|
3209
|
+
declare function camelCase(str: string): string;
|
|
3210
|
+
|
|
3211
|
+
/**
|
|
3212
|
+
* Converts the first character of string to upper case and the remaining to lower case.
|
|
3213
|
+
*
|
|
3214
|
+
* @template T - Literal type of the string.
|
|
3215
|
+
* @param {T} str - The string to be converted to uppercase.
|
|
3216
|
+
* @returns {Capitalize<T>} - The capitalized string.
|
|
3217
|
+
*
|
|
3218
|
+
* @example
|
|
3219
|
+
* const result = capitalize('fred') // returns 'Fred'
|
|
3220
|
+
* const result2 = capitalize('FRED') // returns 'Fred'
|
|
3221
|
+
*
|
|
3222
|
+
* @group Strings
|
|
3223
|
+
*/
|
|
3224
|
+
declare function capitalize<T extends string>(str: T): Capitalize<T>;
|
|
3225
|
+
type Capitalize<T extends string> = T extends `${infer F}${infer R}` ? `${Uppercase<F>}${Lowercase<R>}` : T;
|
|
3226
|
+
|
|
3227
|
+
/**
|
|
3228
|
+
* Converts a value to a string and appends a specified unit to it.
|
|
3229
|
+
* If the value is already a string, it returns it as is, and if the value is a number,
|
|
3230
|
+
* it appends the specified unit (defaults to 'px'). If the value is null, undefined, or an empty string, it returns `undefined`.
|
|
3231
|
+
*
|
|
3232
|
+
* @example
|
|
3233
|
+
* // Adding 'px' unit to a number
|
|
3234
|
+
* convertToUnit(10, 'px'); // '10px';
|
|
3235
|
+
*
|
|
3236
|
+
* // Adding 'em' unit to a number
|
|
3237
|
+
* convertToUnit(5, 'em'); // '5em';
|
|
3238
|
+
*
|
|
3239
|
+
* // Returning a string as is if it's not a number
|
|
3240
|
+
* convertToUnit('100%', 'px'); // '100%';
|
|
3241
|
+
*
|
|
3242
|
+
* // Handling null, undefined, and empty string
|
|
3243
|
+
* convertToUnit(null); // undefined;
|
|
3244
|
+
* convertToUnit(''); // undefined;
|
|
3245
|
+
*
|
|
3246
|
+
* @param str - The value to convert, can be a number, string, null, or undefined.
|
|
3247
|
+
* @param unit - The unit to append to the value. Defaults to 'px'.
|
|
3248
|
+
* @returns The value with the unit appended, or `undefined` if the input is null, undefined, or an empty string.
|
|
3249
|
+
*
|
|
3250
|
+
* @group Strings
|
|
3251
|
+
*/
|
|
3252
|
+
declare function convertToUnit(str: string | number | null | undefined, unit?: string): string | undefined;
|
|
3253
|
+
|
|
3254
|
+
/**
|
|
3255
|
+
* Sanitizes a string by escaping HTML syntax to prevent XSS (Cross-site scripting) attacks.
|
|
3256
|
+
* Converts special HTML characters like `<`, `>`, `&`, etc., into their corresponding HTML entities.
|
|
3257
|
+
*
|
|
3258
|
+
* @example
|
|
3259
|
+
* // Escaping HTML tags to prevent HTML injection
|
|
3260
|
+
* escapeHtml('<b>Strong</b> man.'); // '<b>Strong</b> man.'
|
|
3261
|
+
*
|
|
3262
|
+
* // Escaping other HTML special characters
|
|
3263
|
+
* escapeHtml('<script>alert("XSS")</script>'); // '<script>alert("XSS")</script>'
|
|
3264
|
+
*
|
|
3265
|
+
* @param unsafe - The string to be sanitized (escaped).
|
|
3266
|
+
* @returns A sanitized string with HTML special characters replaced by their corresponding HTML entities.
|
|
3267
|
+
*
|
|
3268
|
+
* @group Strings
|
|
3269
|
+
*/
|
|
3270
|
+
declare function escapeHtml(unsafe: string): string;
|
|
3271
|
+
|
|
3272
|
+
/**
|
|
3273
|
+
* Sanitizes a string by removing all non-numeric characters, leaving only digits.
|
|
3274
|
+
* Useful for extracting numeric values from strings, such as when you want to
|
|
3275
|
+
* extract a number from a string containing units or other non-numeric text.
|
|
3276
|
+
*
|
|
3277
|
+
* @example
|
|
3278
|
+
* // Extracts numeric values from a string with units
|
|
3279
|
+
* escapeNumeric('use 320px'); // '320'
|
|
3280
|
+
*
|
|
3281
|
+
* // Strips out non-numeric characters from a string
|
|
3282
|
+
* escapeNumeric('USD 1,000.50'); // '100050'
|
|
3283
|
+
*
|
|
3284
|
+
* // Returns undefined if no numeric characters are found
|
|
3285
|
+
* escapeNumeric('No numbers here!'); // undefined
|
|
3286
|
+
*
|
|
3287
|
+
* @param str - The input string to be sanitized.
|
|
3288
|
+
* @returns A string containing only the numeric characters, or `undefined` if no numbers are found.
|
|
3289
|
+
*
|
|
3290
|
+
* @group Strings
|
|
3291
|
+
*/
|
|
3292
|
+
declare function escapeNumeric(str: string): string | undefined;
|
|
3293
|
+
|
|
3294
|
+
/**
|
|
3295
|
+
* Escapes special characters in a string to safely use it as a literal pattern in a regular expression.
|
|
3296
|
+
* This function ensures that any characters that would otherwise have a special meaning in a regex
|
|
3297
|
+
* (such as `*`, `+`, `?`, etc.) are properly escaped, allowing them to be used as normal characters
|
|
3298
|
+
* in the pattern.
|
|
3299
|
+
*
|
|
3300
|
+
* @example
|
|
3301
|
+
* // Escapes special characters in the string '[a|b]'
|
|
3302
|
+
* escapeRegExp('[a|b]'); // '\\[a\\|b\\]'
|
|
3303
|
+
*
|
|
3304
|
+
* @example
|
|
3305
|
+
* // Use the function to safely create a regex from user input
|
|
3306
|
+
* const searchTerms = 'Andrew L.';
|
|
3307
|
+
* const searchReg = new RegExp(escapeRegExp(searchTerms), 'i');
|
|
3308
|
+
* const searchResult = users.find(v => searchReg.test(v.name));
|
|
3309
|
+
*
|
|
3310
|
+
* @param str - The string to escape for use in a regular expression.
|
|
3311
|
+
* @returns The input string with all special regex characters escaped.
|
|
3312
|
+
*
|
|
3313
|
+
* @group Strings
|
|
3314
|
+
*/
|
|
3315
|
+
declare function escapeRegExp(str: string): string;
|
|
3316
|
+
|
|
3317
|
+
/**
|
|
3318
|
+
* Extracts the initials from a full name while ignoring titles or prefixes (e.g., Dr., Mr., Mrs.),
|
|
3319
|
+
* as well as any words starting with special characters (e.g., !, @, #).
|
|
3320
|
+
* Handles names with multiple words, ignores special characters, and ensures proper handling of Unicode characters.
|
|
3321
|
+
*
|
|
3322
|
+
* @param {string} fullName - The full name from which to extract initials.
|
|
3323
|
+
* @returns {string} - The extracted initials in uppercase, or an empty string if the input is invalid.
|
|
3324
|
+
*
|
|
3325
|
+
* @example
|
|
3326
|
+
* getInitials("John Doe");
|
|
3327
|
+
* // Returns: "JD"
|
|
3328
|
+
*
|
|
3329
|
+
* @example
|
|
3330
|
+
* getInitials("Dr. Alice Wonderland");
|
|
3331
|
+
* // Returns: "AW"
|
|
3332
|
+
*
|
|
3333
|
+
* @example
|
|
3334
|
+
* getInitials("José María de la Cruz");
|
|
3335
|
+
* // Returns: "JC"
|
|
3336
|
+
*
|
|
3337
|
+
* @example
|
|
3338
|
+
* getInitials("Mr. Albert Einstein");
|
|
3339
|
+
* // Returns: "AE"
|
|
3340
|
+
*
|
|
3341
|
+
* @example
|
|
3342
|
+
* getInitials("Invalid Name");
|
|
3343
|
+
* // Returns: "IN"
|
|
3344
|
+
*
|
|
3345
|
+
* @example
|
|
3346
|
+
* getInitials("");
|
|
3347
|
+
* // Returns: ""
|
|
3348
|
+
*
|
|
3349
|
+
* @group Strings
|
|
3350
|
+
*/
|
|
3351
|
+
declare function getInitials(fullName: string): string;
|
|
3352
|
+
|
|
3353
|
+
declare function getWords(str?: string): string[];
|
|
3354
|
+
|
|
3355
|
+
/**
|
|
3356
|
+
* Checks if the provided URL string has a protocol prefix, such as `http://` or `https://`.
|
|
3357
|
+
* The function checks whether the URL starts with any of the specified protocols (defaults to HTTP and HTTPS).
|
|
3358
|
+
*
|
|
3359
|
+
* This can be useful for validating URLs or ensuring a URL has a valid protocol before using it in network requests.
|
|
3360
|
+
*
|
|
3361
|
+
* @example
|
|
3362
|
+
* hasProtocol('https://google.com'); // true
|
|
3363
|
+
* hasProtocol('http://google.com'); // true
|
|
3364
|
+
* hasProtocol('google.com'); // false
|
|
3365
|
+
*
|
|
3366
|
+
* @param url - The URL string to check.
|
|
3367
|
+
* @param protocols - An array of protocol prefixes to check against (defaults to `['http://', 'https://']`).
|
|
3368
|
+
* @returns `true` if the URL starts with one of the provided protocols, `false` otherwise.
|
|
3369
|
+
*
|
|
3370
|
+
* @group Strings
|
|
3371
|
+
*/
|
|
3372
|
+
declare function hasProtocol(url: string, protocols?: string[]): boolean;
|
|
3373
|
+
|
|
3374
|
+
/**
|
|
3375
|
+
* Encodes a `Uint8Array` or a number array into a hexadecimal string.
|
|
3376
|
+
* Each byte of the array is converted to its corresponding two-character hex representation.
|
|
3377
|
+
*
|
|
3378
|
+
* This function is useful when you need to represent binary data as a string of hexadecimal characters.
|
|
3379
|
+
*
|
|
3380
|
+
* @example
|
|
3381
|
+
* console.log(hex(new Uint8Array([255]))); // 'ff'
|
|
3382
|
+
* console.log(hex([255, 0, 128])); // 'ff0080'
|
|
3383
|
+
*
|
|
3384
|
+
* @param value - The array to be converted, either a `Uint8Array` or a number array.
|
|
3385
|
+
* @returns A string of hexadecimal characters representing the array's byte values.
|
|
3386
|
+
*
|
|
3387
|
+
* @group Strings
|
|
3388
|
+
*/
|
|
3389
|
+
declare function hex(value: Uint8Array | number[]): string;
|
|
3390
|
+
|
|
3391
|
+
/**
|
|
3392
|
+
* Checks if the provided text is a single emoji.
|
|
3393
|
+
* The function uses a regular expression to match the emoji and ensures that the entire string is a valid single emoji.
|
|
3394
|
+
*
|
|
3395
|
+
* @param {unknown} text - The input value to check.
|
|
3396
|
+
* @returns {boolean} - Returns `true` if the input is a single emoji, otherwise `false`.
|
|
3397
|
+
*
|
|
3398
|
+
* @example
|
|
3399
|
+
* isOneEmoji("😊"); // Returns: true
|
|
3400
|
+
* isOneEmoji("Hello 😊"); // Returns: false
|
|
3401
|
+
* isOneEmoji("😎"); // Returns: true
|
|
3402
|
+
* isOneEmoji("👨👩👧👦"); // Returns: true (family emoji with multiple characters)
|
|
3403
|
+
* isOneEmoji("not an emoji"); // Returns: false
|
|
3404
|
+
*
|
|
3405
|
+
* @group Strings
|
|
3406
|
+
*/
|
|
3407
|
+
declare function isOneEmoji(text: unknown): text is string;
|
|
3408
|
+
|
|
3409
|
+
/**
|
|
3410
|
+
* Converts a two-letter ISO country code (e.g., 'US') to the corresponding flag emoji.
|
|
3411
|
+
* If the input is not a valid two-letter country code, it returns the original string.
|
|
3412
|
+
*
|
|
3413
|
+
* @param {string} iso - The two-letter ISO country code.
|
|
3414
|
+
* @returns {string} - The corresponding country flag emoji or the original input if it's invalid.
|
|
3415
|
+
*
|
|
3416
|
+
* @example
|
|
3417
|
+
* isoToFlagEmoji("US"); // Returns: 🇺🇸
|
|
3418
|
+
* isoToFlagEmoji("GB"); // Returns: 🇬🇧
|
|
3419
|
+
* isoToFlagEmoji("DE"); // Returns: 🇩🇪
|
|
3420
|
+
* isoToFlagEmoji("xyz"); // Returns: "xyz" (invalid code)
|
|
3421
|
+
*
|
|
3422
|
+
* @group Strings
|
|
3423
|
+
*/
|
|
3424
|
+
declare function isoToFlagEmoji(iso: string): string;
|
|
3425
|
+
|
|
3426
|
+
/**
|
|
3427
|
+
* Converts a string to kebab case.
|
|
3428
|
+
*
|
|
3429
|
+
* Kebab case is the naming convention in which each word is written in lowercase and separated by a dash (-) character.
|
|
3430
|
+
*
|
|
3431
|
+
* @param {string} str - The string that is to be changed to kebab case.
|
|
3432
|
+
* @returns {string} - The converted string to kebab case.
|
|
3433
|
+
*
|
|
3434
|
+
* @example
|
|
3435
|
+
* const convertedStr1 = kebabCase('camelCase') // returns 'camel-case'
|
|
3436
|
+
* const convertedStr2 = kebabCase('some whitespace') // returns 'some-whitespace'
|
|
3437
|
+
* const convertedStr3 = kebabCase('hyphen-text') // returns 'hyphen-text'
|
|
3438
|
+
* const convertedStr4 = kebabCase('HTTPRequest') // returns 'http-request'
|
|
3439
|
+
*
|
|
3440
|
+
* @group Strings
|
|
3441
|
+
*/
|
|
3442
|
+
declare function kebabCase(str: string): string;
|
|
3443
|
+
|
|
3444
|
+
/**
|
|
3445
|
+
* Converts a string to lower case.
|
|
3446
|
+
*
|
|
3447
|
+
* Lower case is the naming convention in which each word is written in lowercase and separated by an space ( ) character.
|
|
3448
|
+
*
|
|
3449
|
+
* @param {string} str - The string that is to be changed to lower case.
|
|
3450
|
+
* @returns {string} - The converted string to lower case.
|
|
3451
|
+
*
|
|
3452
|
+
* @example
|
|
3453
|
+
* const convertedStr1 = lowerCase('camelCase') // returns 'camel case'
|
|
3454
|
+
* const convertedStr2 = lowerCase('some whitespace') // returns 'some whitespace'
|
|
3455
|
+
* const convertedStr3 = lowerCase('hyphen-text') // returns 'hyphen text'
|
|
3456
|
+
* const convertedStr4 = lowerCase('HTTPRequest') // returns 'http request'
|
|
3457
|
+
*
|
|
3458
|
+
* @group Strings
|
|
3459
|
+
*/
|
|
3460
|
+
declare const lowerCase: (str?: string) => string;
|
|
3461
|
+
|
|
3462
|
+
/**
|
|
3463
|
+
* Masks part of the email address to provide a simple level of privacy.
|
|
3464
|
+
* The username part is partially masked with asterisks, while the domain remains intact.
|
|
3465
|
+
*
|
|
3466
|
+
* ⚠️ Returns an empty string if the provided value is invalid.
|
|
3467
|
+
*
|
|
3468
|
+
* @example
|
|
3469
|
+
* maskingEmail('andrew@gmail.com'); // 'a****w@gmail.com'
|
|
3470
|
+
* maskingEmail('user@domain.com'); // 'u***r@domain.com'
|
|
3471
|
+
* maskingEmail('invalidemail'); // ''
|
|
3472
|
+
*
|
|
3473
|
+
* @param value - The email address to be masked.
|
|
3474
|
+
* @returns The masked email address or an empty string if the value is invalid.
|
|
3475
|
+
*
|
|
3476
|
+
* @group Strings
|
|
3477
|
+
*/
|
|
3478
|
+
declare function maskingEmail(value: string): string;
|
|
3479
|
+
|
|
3480
|
+
/**
|
|
3481
|
+
* Masks part of a phone number to provide a simple level of privacy.
|
|
3482
|
+
* The function replaces digits in a specified range with a given character.
|
|
3483
|
+
* Supports formatted phone numbers (e.g., `(000) 000-11-11`).
|
|
3484
|
+
*
|
|
3485
|
+
* ⚠️ Returns an empty string if the provided value is invalid.
|
|
3486
|
+
*
|
|
3487
|
+
* @example
|
|
3488
|
+
* maskingPhone('+18000551100'); // '+18XXXXX1100'
|
|
3489
|
+
* maskingPhone('+18000551100', 2, 4, '*'); // '+18*****1100'
|
|
3490
|
+
* maskingPhone('+1 800-055-1100'); // '+1 8XX-XXX-1100'
|
|
3491
|
+
* maskingPhone('+1234567890', 3, 5, 'X'); // '+1XXX567890'
|
|
3492
|
+
*
|
|
3493
|
+
* @param value - The phone number to be masked.
|
|
3494
|
+
* @param [fromPosition=2] - The starting position from left side where masking begins (default is 2).
|
|
3495
|
+
* @param [toPosition=4] - The position from right side where masking ends (default is 4).
|
|
3496
|
+
* @param [withChar='X'] - The character used to replace digits (default is 'X').
|
|
3497
|
+
* @returns The masked phone number or an empty string if the value is invalid.
|
|
3498
|
+
*
|
|
3499
|
+
* @group Strings
|
|
3500
|
+
*/
|
|
3501
|
+
declare function maskingPhone(value: string, fromPosition?: number, toPosition?: number, withChar?: string): string;
|
|
3502
|
+
|
|
3503
|
+
/**
|
|
3504
|
+
* Masks the middle characters of each word in the given string, leaving the first and last characters intact.
|
|
3505
|
+
* The characters in the middle of each word are replaced by a specified masking character (default is `*`).
|
|
3506
|
+
*
|
|
3507
|
+
* ⚠️ If the provided value is not a valid string, the function returns an empty string.
|
|
3508
|
+
*
|
|
3509
|
+
* **Note**: This function does not perform any validation or checks for non-alphabetic characters within words.
|
|
3510
|
+
* It simply masks all characters between the first and last character of each word.
|
|
3511
|
+
*
|
|
3512
|
+
* @param {string} value - The input string containing words to be masked.
|
|
3513
|
+
* @param {string} [withChar='*'] - The character used to replace the middle characters of each word. Default is `*`.
|
|
3514
|
+
*
|
|
3515
|
+
* @returns {string} The input string with middle characters of words masked, or an empty string if the input is invalid.
|
|
3516
|
+
*
|
|
3517
|
+
* @example
|
|
3518
|
+
* maskingWords('hello world'); // 'h**o w**d'
|
|
3519
|
+
* maskingWords('John Doe'); // 'J**n D**e'
|
|
3520
|
+
* maskingWords('a b c'); // '* * *'
|
|
3521
|
+
*
|
|
3522
|
+
* @group Strings
|
|
3523
|
+
*/
|
|
3524
|
+
declare function maskingWords(value: string, withChar?: string): string;
|
|
3525
|
+
|
|
3526
|
+
/**
|
|
3527
|
+
* Useful when you need to generate almost secure object id in browser
|
|
3528
|
+
*
|
|
3529
|
+
* Based on [bson](https://github.com/mongodb/js-bson/blob/main/src/objectid.ts)
|
|
3530
|
+
*
|
|
3531
|
+
* @example
|
|
3532
|
+
* const userId = objectId(); // '67350af7885ba34010c83859'
|
|
3533
|
+
*
|
|
3534
|
+
* @group Strings
|
|
3535
|
+
*/
|
|
3536
|
+
declare function objectId(fromValue?: number | Date): string;
|
|
3537
|
+
|
|
3538
|
+
/**
|
|
3539
|
+
* Generates a random string of the specified length using characters from a predefined set.
|
|
3540
|
+
* The characters used in the generated string include lowercase letters (a-z) and digits (0-9).
|
|
3541
|
+
*
|
|
3542
|
+
* @param {number} length - The length of the random string to generate. Must be a positive integer.
|
|
3543
|
+
*
|
|
3544
|
+
* @returns {string} A random string of the specified length, composed of characters from 'a-z' and '0-9'.
|
|
3545
|
+
*
|
|
3546
|
+
* @example
|
|
3547
|
+
* randomString(8); // e.g. 'a1b2c3d4'
|
|
3548
|
+
* randomString(12); // e.g. '3f6g7h8i9j0k'
|
|
3549
|
+
* randomString(5); // e.g. '1a2b3'
|
|
3550
|
+
*
|
|
3551
|
+
* @group Strings
|
|
3552
|
+
*/
|
|
3553
|
+
declare function randomString(length: number): string;
|
|
3554
|
+
|
|
3555
|
+
/**
|
|
3556
|
+
* Converts a string to snake case.
|
|
3557
|
+
*
|
|
3558
|
+
* Snake case is the naming convention in which each word is written in lowercase and separated by an underscore (_) character.
|
|
3559
|
+
*
|
|
3560
|
+
* @param {string} str - The string that is to be changed to snake case.
|
|
3561
|
+
* @returns {string} - The converted string to snake case.
|
|
3562
|
+
*
|
|
3563
|
+
* @example
|
|
3564
|
+
* const convertedStr1 = snakeCase('camelCase') // returns 'camel_case'
|
|
3565
|
+
* const convertedStr2 = snakeCase('some whitespace') // returns 'some_whitespace'
|
|
3566
|
+
* const convertedStr3 = snakeCase('hyphen-text') // returns 'hyphen_text'
|
|
3567
|
+
* const convertedStr4 = snakeCase('HTTPRequest') // returns 'http_request'
|
|
3568
|
+
*
|
|
3569
|
+
* @group Strings
|
|
3570
|
+
*/
|
|
3571
|
+
declare const snakeCase: (str?: string) => string;
|
|
3572
|
+
|
|
3573
|
+
/**
|
|
3574
|
+
* Formats a string by replacing format specifiers with values from the provided arguments.
|
|
3575
|
+
* It supports a variety of format types, including strings, numbers, and objects.
|
|
3576
|
+
*
|
|
3577
|
+
* ⚠️ This function mutates the `unusedArgs` array, which will contain any arguments
|
|
3578
|
+
* that were not used in the formatting process.
|
|
3579
|
+
*
|
|
3580
|
+
* @param line - The format string containing placeholders to be replaced by arguments.
|
|
3581
|
+
* Format specifiers are indicated by the `%` symbol, followed by a character indicating
|
|
3582
|
+
* the type of argument to insert (e.g., `%s` for string, `%d` for integer, `%f` for float).
|
|
3583
|
+
* @param args - The array of arguments to replace the format specifiers in the string.
|
|
3584
|
+
* The function will iterate over the arguments and substitute them into the format string
|
|
3585
|
+
* in the order they appear.
|
|
3586
|
+
* @param [unusedArgs=[]] - The array that will collect any unused arguments
|
|
3587
|
+
* that were not needed for formatting. This array is mutated by the function.
|
|
3588
|
+
*
|
|
3589
|
+
* @returns {string} The formatted string with placeholders replaced by corresponding arguments.
|
|
3590
|
+
*
|
|
3591
|
+
* @example
|
|
3592
|
+
* const unusedArgs: any[] = [];
|
|
3593
|
+
*
|
|
3594
|
+
* console.log(sprintf('Hello %s', ['World', 'Great'], unusedArgs));
|
|
3595
|
+
* // Output: 'Hello World'
|
|
3596
|
+
* console.log(unusedArgs);
|
|
3597
|
+
* // Output: ['Great']
|
|
3598
|
+
*
|
|
3599
|
+
* @example
|
|
3600
|
+
* console.log(sprintf('I have %d apples and %f.5 liters of water.', [5, 3.2], unusedArgs));
|
|
3601
|
+
* // Output: 'I have 5 apples and 3.2 liters of water.'
|
|
3602
|
+
* console.log(unusedArgs);
|
|
3603
|
+
* // Output: []
|
|
3604
|
+
*
|
|
3605
|
+
* @group Strings
|
|
3606
|
+
*/
|
|
3607
|
+
declare function sprintf(line: string, args: any[], unusedArgs?: any[]): string;
|
|
3608
|
+
|
|
3609
|
+
/**
|
|
3610
|
+
* Converts the first character of each word in a string to uppercase and the remaining characters to lowercase.
|
|
3611
|
+
*
|
|
3612
|
+
* Start case is the naming convention in which each word is written with an initial capital letter.
|
|
3613
|
+
* @param {string} str - The string to convert.
|
|
3614
|
+
* @returns {string} The converted string.
|
|
3615
|
+
*
|
|
3616
|
+
* @example
|
|
3617
|
+
* const result1 = startCase('hello world'); // result will be 'Hello World'
|
|
3618
|
+
* const result2 = startCase('HELLO WORLD'); // result will be 'Hello World'
|
|
3619
|
+
* const result3 = startCase('hello-world'); // result will be 'Hello World'
|
|
3620
|
+
* const result4 = startCase('hello_world'); // result will be 'Hello World'
|
|
3621
|
+
*
|
|
3622
|
+
* @group Strings
|
|
3623
|
+
*/
|
|
3624
|
+
declare const startCase: (value?: string) => string;
|
|
3625
|
+
|
|
3626
|
+
/**
|
|
3627
|
+
* Replaces placeholders in the input string with values from the provided object.
|
|
3628
|
+
* The placeholders are denoted by `{{ key }}` syntax, where `key` is a property name in the object.
|
|
3629
|
+
* The function optionally allows a custom method to handle how the values are retrieved from the object.
|
|
3630
|
+
*
|
|
3631
|
+
* @param {string} str - The string with placeholders to be replaced. Placeholders are in the form of `{{key}}`.
|
|
3632
|
+
* @param {T} obj - The object whose properties will be used to replace the placeholders in the string.
|
|
3633
|
+
* @param method - An optional custom method
|
|
3634
|
+
* to retrieve values from the object. The default method retrieves
|
|
3635
|
+
* the values by accessing the object property directly using the `key`.
|
|
3636
|
+
*
|
|
3637
|
+
* @returns {string} The string with placeholders replaced by the corresponding values from the object.
|
|
3638
|
+
*
|
|
3639
|
+
* @example
|
|
3640
|
+
* const context = { name: 'Andrew', age: 30 };
|
|
3641
|
+
* console.log(strAssign('Hey {{ name }}! You are {{ age }} years old.', context));
|
|
3642
|
+
* // Output: 'Hey Andrew! You are 30 years old.'
|
|
3643
|
+
*
|
|
3644
|
+
* @example
|
|
3645
|
+
* // Using a custom method
|
|
3646
|
+
* const context2 = { firstName: 'Andrew', lastName: 'L.' };
|
|
3647
|
+
* const customMethod = (obj, key) => {
|
|
3648
|
+
* if (key === 'name') {
|
|
3649
|
+
* return obj.firstName + ' ' + obj.lastName;
|
|
3650
|
+
* }
|
|
3651
|
+
* return obj[key];
|
|
3652
|
+
* };
|
|
3653
|
+
* console.log(strAssign('Hello {{ name }}!', context2, customMethod));
|
|
3654
|
+
* // Output: 'Hello Andrew L.!'
|
|
3655
|
+
*
|
|
3656
|
+
* @group Strings
|
|
3657
|
+
*/
|
|
3658
|
+
declare function strAssign<T extends object>(str: string, obj: T, method?: (obj: T, key: string) => any): string;
|
|
3659
|
+
|
|
3660
|
+
/**
|
|
3661
|
+
* Truncates a string to the specified maximum length while preserving whole words
|
|
3662
|
+
* and appends ellipsis (`...`) if the string exceeds the maximum length.
|
|
3663
|
+
* Ensures that truncation does not occur if the difference is insignificant
|
|
3664
|
+
* (less than 5% of the original string length).
|
|
3665
|
+
*
|
|
3666
|
+
* @param {string} str - The input string to truncate.
|
|
3667
|
+
* @param {number} maxLength - The maximum allowed length for the string.
|
|
3668
|
+
* @param {number} insignificantThreshold - The insignificance threshold as a fraction of the original string length (default is 5%)
|
|
3669
|
+
* @returns {string} - The truncated string with ellipsis if applicable.
|
|
3670
|
+
*
|
|
3671
|
+
*
|
|
3672
|
+
* @example
|
|
3673
|
+
* // Basic truncation
|
|
3674
|
+
* truncate("This is a test string for truncation.", 20);
|
|
3675
|
+
* // Returns: "This is a test..."
|
|
3676
|
+
*
|
|
3677
|
+
* @example
|
|
3678
|
+
* // No truncation needed as the string length is within the limit
|
|
3679
|
+
* truncate("Short string", 20);
|
|
3680
|
+
* // Returns: "Short string"
|
|
3681
|
+
*
|
|
3682
|
+
* @example
|
|
3683
|
+
* // No truncation because the difference is insignificant
|
|
3684
|
+
* truncate("This string has an insignificant truncation.", 40);
|
|
3685
|
+
* // Returns: "This string has an insignificant truncation."
|
|
3686
|
+
*
|
|
3687
|
+
* @example
|
|
3688
|
+
* // Handles strings with no spaces gracefully
|
|
3689
|
+
* truncate("ThisStringHasNoSpacesButIsVeryLong", 10);
|
|
3690
|
+
* // Returns: "ThisString..."
|
|
3691
|
+
*
|
|
3692
|
+
* @group Strings
|
|
3693
|
+
*/
|
|
3694
|
+
declare function truncate(value: string, maxLength?: number, insignificantThreshold?: number): string;
|
|
3695
|
+
|
|
3696
|
+
declare function removeVS16s(rawEmoji: string): string;
|
|
3697
|
+
declare const _default: RegExp;
|
|
3698
|
+
|
|
3699
|
+
/**
|
|
3700
|
+
* Truncates the input string to the specified maximum length and appends an ellipsis (`...`)
|
|
3701
|
+
* if the string exceeds the maximum length. If the string is shorter than or equal to the
|
|
3702
|
+
* maximum length, it is returned unchanged.
|
|
3703
|
+
*
|
|
3704
|
+
* Unlike the `truncate` function, the result can be truncated in the middle of a word
|
|
3705
|
+
*
|
|
3706
|
+
* @param {string} value - The input string to truncate.
|
|
3707
|
+
* @param {number} maxLength - The maximum allowed length for the string (default is 30).
|
|
3708
|
+
* @returns {string} - The truncated string with ellipsis (`...`) if necessary.
|
|
3709
|
+
*
|
|
3710
|
+
* @example
|
|
3711
|
+
* wrapText("This is a long string", 10); // Returns: "This is a..."
|
|
3712
|
+
* wrapText("Short text", 20); // Returns: "Short text"
|
|
3713
|
+
* wrapText("Another long string example", 15); // Returns: "Another long..."
|
|
3714
|
+
*
|
|
3715
|
+
* @group Strings
|
|
3716
|
+
*/
|
|
3717
|
+
declare function wrapText(value: string, maxLength?: number): string;
|
|
3718
|
+
|
|
3719
|
+
/**
|
|
3720
|
+
* Transform value to error object
|
|
3721
|
+
* @group Errors
|
|
3722
|
+
*/
|
|
3723
|
+
declare function toError<T>(value: T, unknownMessage?: string): T extends Error ? T : Error;
|
|
3724
|
+
|
|
3725
|
+
export { type AnyFunction, AppError, type ArgumentsType, type Arrayable, AsyncIterableQueue, type Awaitable, BrowserAssertionError, CancellablePromise, Color, type ColorChannels, ColorParser, type Data, type DeepPartial, type Defer, type EnvParser, type ExecResult, type ExecResultToSkip, type ExecResultToSuccess, type ExecSkip, type ExecSuccess, FixedMap, FixedWeakMap, type Fn, type FormatMoney, type FormatNumber, type FunctionArgs, type GenericObject, type IfAny, type IsAny, type LiteralUnion, type Logger, LruCache, type Nothing, type OverwriteWith, type Prettify, type Primitive, type PromisifyFn, Queue, type RandomizerOptions, type RetryOnErrorConfig, type SelectOptionItem, type SelectOptions, type SimpleDefaultEventMap, SimpleEventEmitter, type SimpleEventMap, _default as TWEMOJI_REGEX, type ThemeConfig, TimeBucket, type TimeBucketOptions, type TimeObject, type TypeOf, type TypeOfMap, type ValuesOfObject, type WithCache, type WithCacheBucketBatchOptions, type WithCacheBucketOptions, type WithCacheFixedOptions, type WithCacheLruOptions, type WithCacheOptions, type WithCachePointer, type WithCacheResult, type WithCacheStorage, type WithCustomizer, type WithCustomizerFactory, type WithCustomizerValue, alpha, arrayable, assert, asyncFilter, asyncFind, asyncForEach, asyncMap, avg, blendColors, buildCssColor, cache, cacheBucket, cacheFixed, cacheLRU, camelCase, capitalize, captureStackTrace, catchError, channelsToHSL, channelsToHex, channelsToRGB, checkBitmask, chunk, chunkSeries, clamp, cleanEmpty, cleanObject, colorToChannels, contrastRatio, convertToUnit, crc32, createCustomizer, createCustomizerFactory, createDeepCloneWith, createEnvParser, createRandomizer, createSecureCustomizer, createWithCache, cssVariable, deepAssign, deepClone, deepCloneWith, deepDefaults, deepFreeze, def, defer, delay, dropCache, env, escapeHtml, escapeNumeric, escapeRegExp, fastIdle, fastIdlePromise, fastRaf, findMean, flagsToMap, flatten, formatMoney, formatNumber, get, getFileExtension, getFileName, getInitials, getRandomInt, getWords, has, hasOwn, hasProtocol, hex, hexToChannels, hslToChannels, humanFileSize, humanize, interpolateColor, isBigInt, isBoolean, isCached, isClient, isColorChannels, isCustomizerFactory, isDate, isDef, isEmpty, isEqual, isError, isFunction, isMap, isNullOrUndefined, isNumber, isObject, isOneEmoji, isPrimitive, isPromise, isSet, isSkip, isString, isSuccess, isSymbol, isWeakMap, isWeakSet, isWithCache, isoToFlagEmoji, kebabCase, keyBy, logger, lowerCase, luminance, maskingEmail, maskingPhone, maskingWords, nextTickIteration, noop, objectId, omit, omitPrefixed, orderBy, parseAllNumbers, parseAlpha, parsePercentage, percentOf, pick, pickPrefixed, qs, rafPromise, randomString, removeVS16s, retryOnError, rgbToChannels, round2digits, set, snakeCase, sprintf, startCase, strAssign, sum, timeout, timestamp, timestampToDate, tintedTextColor, toError, toMap, truncate, typeOf, unflatten, union, uniq, uniqBy, unset, withCache, withCacheBucket, withCacheBucketBatch, withCacheFixed, withCacheLRU, withDeepClone, withPointerCache, wrapText };
|