@superutils/core 1.0.0

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.
@@ -0,0 +1,1320 @@
1
+ /**
2
+ * Defines an async function
3
+ */
4
+ type AsyncFn<TOut = unknown, TArgs extends unknown[] = []> = (...args: TArgs) => Promise<Awaited<TOut>>;
5
+ /**
6
+ * Create a tuple of specific type with given length
7
+ * ---
8
+ * @example Create a new tuple
9
+ * ```typescript
10
+ * type CreatedTuple = CreateTuple<number, 3>
11
+ * // Result: [number, number, number]
12
+ * ```
13
+ *
14
+ * @example Create a new tuple by extending an existing tuple
15
+ * ```typescript
16
+ * type ExtendedTuple = CreateTuple<string, 6, CreatedTuple>
17
+ * // Result: [number, number, number, string, string, string]
18
+ * ```
19
+ */
20
+ type CreateTuple<T, Length extends number, Output extends readonly unknown[] = []> = Output['length'] extends Length ? Output : CreateTuple<T, Length, [...Output, T]>;
21
+ /**
22
+ * A recursive helper type that defines the signature of the curry function.
23
+ * @template TParams The tuple of remaining parameters.
24
+ * @template TData The final return type.
25
+ */
26
+ type Curry<TData, TParams extends unknown[]> = <TArgs extends unknown[]>(...args: TArgs & KeepFirstN<TParams, TArgs['length']>) => DropFirstN<TParams, TArgs['length']> extends [unknown, ...unknown[]] ? Curry<TData, DropFirstN<TParams, TArgs['length']>> : TData;
27
+ /**
28
+ * Deferred function config
29
+ */
30
+ interface DeferredConfig<ThisArg = unknown> {
31
+ leading?: boolean | 'global';
32
+ onError?: (err: unknown) => ValueOrPromise<unknown>;
33
+ thisArg?: ThisArg;
34
+ tid?: TimeoutId;
35
+ }
36
+ /**
37
+ * Drop the first item from an array/tuple and keep the rest
38
+ * ---
39
+ * @example usage
40
+ * ```typescript
41
+ * type MyTuple = [first: string, second: number, third: boolean]
42
+ * type MyTupleWOFirst = DropFirst<MyTuple> // result: [second: number, third: boolean]
43
+ * ```
44
+ */
45
+ type DropFirst<T extends unknown[]> = T extends [unknown, ...infer Rest] ? Rest : [];
46
+ /**
47
+ * Drop first N items from an array/tuple and keep the rest
48
+ * ---
49
+ * @example usage
50
+ * ```typescript
51
+ * type MyTuple = [first: string, second: number, third: boolean]
52
+ * type MyTupleWO2 = DropFirstN<MyTuple, 2> // result: [third: boolean]
53
+ * ```
54
+ */
55
+ type DropFirstN<T extends unknown[], N extends number, Dropped extends unknown[] = []> = TupleMaxLength<Dropped> extends N ? T : T extends [infer First, ...infer Rest] ? DropFirstN<Rest, N, [...Dropped, First]> : never;
56
+ /**
57
+ * Drop the last item from an array/tuple and keep the rest
58
+ * ---
59
+ * @example usage
60
+ * ```typescript
61
+ * type MyTuple = [first: string, second: number, third: boolean]
62
+ * type MyTupleWOLast = DropLast<MyTuple> // result: [first: string, second: number]
63
+ * ```
64
+ */
65
+ type DropLast<T extends unknown[]> = T extends [...infer Rest, unknown] ? Rest : [];
66
+ type IsFiniteTuple<T extends unknown[]> = number extends T['length'] ? false : true;
67
+ type IsOptional<T, K extends keyof T> = {} extends Pick<T, K> ? true : false;
68
+ /**
69
+ * Keep the first item from an array/tuple and drop the rest
70
+ * ---
71
+ * @example usage
72
+ * ```typescript
73
+ * type MyTuple = [first: string, second: number, third: boolean]
74
+ * type MyTupleWFirst = KeepFirst<MyTuple> // result: [first: string]
75
+ * ```
76
+ */
77
+ type KeepFirst<T extends unknown[]> = T extends readonly [
78
+ infer First,
79
+ ...DropFirst<T>
80
+ ] ? [First] : never;
81
+ /**
82
+ * Keep first N items from an array/tuple and drop the rest
83
+ * ---
84
+ * @example usage
85
+ * ```typescript
86
+ * type MyTuple = [first: string, second: number, third: boolean]
87
+ * type MyTupleWith1st2 = KeepFirstN<MyTuple, 2> // result: [first: string, second: number]
88
+ * ```
89
+ */
90
+ type KeepFirstN<T extends readonly unknown[], N extends number = 1> = TupleMaxLength<T> extends N ? T : T extends readonly [...infer TWithoutLast, unknown] ? KeepFirstN<TWithoutLast, N> : never;
91
+ /**
92
+ * Extract optional members of a tuple.
93
+ *
94
+ * @template Tuple tuple
95
+ * @template Require (optional) if true, all returned member of the returned tuple will be required field and TAlt will be added as union.
96
+ * Defaults to `false`
97
+ * @template TAlt (optional) Defaults to `undefined`
98
+ *
99
+ * @example usage
100
+ * ```typescript
101
+ * import { KeepOptionals } from '@superutils/core
102
+ * type MyTuple = [first: string, second?: number, third?: boolean]
103
+ * type Optionals = KeepOptionals<MyTuple>
104
+ * // Result: [second?: number, third?: boolean]
105
+ * type AsRequired = KeepOptionals<MyTuple, true>
106
+ * // Result: [second: number | undefined, third: boolean | undefined]
107
+ * type AsRequiredWNull = KeepOptionals<MyTuple, true, null>
108
+ * // Result: [second: number | null, third: boolean | null]
109
+ * ```
110
+ */
111
+ type KeepOptionals<Tuple extends unknown[], Require extends true | false = false, TAlt = undefined> = Require extends true ? Required<DropFirstN<Tuple, Tuple['length']>> extends [...infer Optionals] ? TupleWithAlt<Optionals, TAlt> : never : DropFirstN<Tuple, Tuple['length']>;
112
+ /**
113
+ * Extract all required members of a tuple
114
+ */
115
+ type KeepRequired<T extends unknown[]> = KeepFirstN<Required<T>, // force all members to be required to avoid getting `never` because of optional members
116
+ MinLength<T>>;
117
+ type MinLength<T extends unknown[], Count extends unknown[] = []> = T extends [infer F, ...infer R] ? undefined extends F ? MinLength<R, Count> : MinLength<R, [...Count, unknown]> : Count['length'];
118
+ /** Make T1 optional if T2 is undefined */
119
+ type OptionalIf<T1, T2, T2IF = undefined, T1Alt = undefined> = T2 extends T2IF ? T1 : T1 | T1Alt;
120
+ type MakeOptional<Tuple extends unknown[], IndexStart extends number, IndexEnd extends number = TupleMaxLength<Tuple>> = Tuple extends readonly [
121
+ ...infer Left,
122
+ ...Slice<Tuple, IndexStart, IndexEnd>,
123
+ ...infer Right
124
+ ] ? [...Left, ...Partial<Slice<Tuple, IndexStart>>, ...Right] : never;
125
+ /**
126
+ * Create a new slices tuple from an existing tuple
127
+ * ---
128
+ * @example usage
129
+ * ```typescript
130
+ * type MyTuple = [a: string, b: boolean, c: number, d: Record<string, unknown>]
131
+ * type FirstHalf = Slice<MyTuple, 0, 2>
132
+ * type LastHalf = Slice<MyTuple, 2>
133
+ * ```
134
+ */
135
+ type Slice<Tuple extends unknown[], IndexStart extends number, IndexEnd extends number = TupleMaxLength<Tuple>> = [...KeepRequired<Tuple>, ...KeepOptionals<Tuple, true>] extends [
136
+ ...infer All
137
+ ] ? DropFirstN<KeepFirstN<All, IndexEnd>, IndexStart> extends [
138
+ ...infer Sliced
139
+ ] ? Sliced : never : never;
140
+ type TimeoutId = Parameters<typeof clearTimeout>[0];
141
+ /**
142
+ * Get the maximum possible length of a tuple
143
+ *
144
+ * This is particularly useful when a tuple (or function paramenters) contains optional members.
145
+ *
146
+ * ---
147
+ * @example usage
148
+ * ```typescript
149
+ * type MyTuple = [string, number?, boolean?]
150
+ * type Lengths = MyTuple['length'] // 1 | 2 | 3 // union because of optional parameters
151
+ * type MaxLength = TupleMaxLength<MyTuple> // 3
152
+ * ```
153
+ */
154
+ type TupleMaxLength<T extends readonly unknown[]> = Required<T>['length'];
155
+ /**
156
+ * Add alt type to all members of a tuple.
157
+ *
158
+ * ---
159
+ * @example usage
160
+ * ```typescript
161
+ * type MyTuple = [first: boolean, second: string]
162
+ * type MyTupleWithUndefined = TupleWithAlt<MyTuple>
163
+ * // Result: [first: boolean | undefined, second: string | undefined]
164
+ * type MyTupleWithNull = TupleWithAlt<MyTuple, null>
165
+ * // Result: [first: boolean | null, second: string | null]
166
+ * ```
167
+ */
168
+ type TupleWithAlt<Tuple extends unknown[], TAlt = undefined> = {
169
+ -readonly [K in keyof Tuple]: Tuple[K] | TAlt;
170
+ };
171
+ /**
172
+ * Accept value or a function that returns the value
173
+ *
174
+ * Examples:
175
+ * ---
176
+ * @example usage
177
+ * ```typescript
178
+ * import { isFn, ValueOrFunc } from '@superutils/core'
179
+ * const print = (value: ValueOrFunc<string>) => isFn(value)
180
+ * ? value()
181
+ * : value
182
+ * print('Print me!')
183
+ * print(() => 'Print me too!')
184
+ * ```
185
+ */
186
+ type ValueOrFunc<Value, Args extends unknown[] = []> = Value | ((...args: Args) => Value);
187
+ /** Accept value a promise resolving to value */
188
+ type ValueOrPromise<T> = T | Promise<T>;
189
+
190
+ /**
191
+ * Creates a curried version of a function. The curried function can be
192
+ * called with one or more or all arguments at a time. Once all arguments have been
193
+ * supplied, the original function is executed.
194
+ *
195
+ * ---
196
+ *
197
+ * PS:
198
+ * ---
199
+ * To get around Typescript's limitations, all optional parameters to will be
200
+ * turned required and unioned with `undefined`.
201
+ *
202
+ * ---
203
+ *
204
+ * @param func The function to curry.
205
+ * @returns A new, curried function that is fully type-safe.
206
+
207
+ *
208
+ * @example Convert any function into a curried function
209
+ * ```typescript
210
+ * const func = (
211
+ * first: string,
212
+ * second: number,
213
+ * third?: boolean,
214
+ * fourth?: string
215
+ * ) => `${first}-${second}-${third}-${fourth}`
216
+ * // We create a new function from the `func()` function that acts like a type-safe curry function
217
+ * // while also being flexible with the number of arguments supplied.
218
+ * const curriedFunc = curry(func)
219
+ *
220
+ * // Example 1: usage like a regular curry function and provide one argument at a time.
221
+ * // Returns a function expecting args: second, third, fourth
222
+ * const fnWith1 = curriedFunc('first')
223
+ * // Returns a function expecting args: third, fourth
224
+ * const fnWith2 = fnWith1(2)
225
+ * // returns a function epecting only fourth arg
226
+ * const fnWith3 = fnWith2(false)
227
+ * // All args are now provided, the original function is called and result is returned.
228
+ * const result = fnWith3('last')
229
+ * ```
230
+ *
231
+ * @example Flexible curried function arguments
232
+ * ```typescript
233
+ * // Provide as many arguments as you wish. Upto the limit of the original function.
234
+ * // Returns a function expecting only the remaining argument(s)
235
+ * const fnWith3 = curriedFunc('first', 2, false)
236
+ * // All args provided, returns the result
237
+ * const result = fnWith3('last')
238
+ * ```
239
+ *
240
+ * @example Early invocation using "arity".
241
+ * Useful when a function has
242
+ * - non-finite arguments (eg: number[])
243
+ * - optional arguments and you do not want to avoid one or more optional arguments
244
+ * ```typescript
245
+ * const curriedWArity3 = curry(func, 3)
246
+ * const result = curriedWArity3('first', 2, false)
247
+ * ```
248
+ */
249
+ declare function curry<TData, TArgs extends unknown[], TArgsIsFinite extends boolean = IsFiniteTuple<TArgs>, TArity extends TArgs['length'] = TArgsIsFinite extends true ? TupleMaxLength<TArgs> : number>(func: (...args: TArgs) => TData, ...[arity]: TArgsIsFinite extends true ? [arity?: TArity] : [
250
+ arity: TArity
251
+ ]): Curry<TData, CurriedArgs<TArgs, TArgsIsFinite, (...args: TArgs) => TData, TArity>>;
252
+ type CurriedArgs<TArgs extends unknown[], TArgsIsFinite extends boolean, TFunc extends (...args: any[]) => unknown, TArity extends number> = TArgsIsFinite extends false ? CreateTuple<Parameters<TFunc>[number], TArity> : KeepFirstN<[
253
+ ...KeepRequired<TArgs>,
254
+ ...KeepOptionals<TArgs, true, undefined>
255
+ ], TArity>;
256
+
257
+ /**
258
+ * @function deferred AKA debounce
259
+ * @summary returns a function that invokes the callback function after certain delay/timeout.
260
+ * All errors will be gracefully swallowed.
261
+ *
262
+ * @param callback function to be invoked after timeout
263
+ * @param delay (optional) timeout duration in milliseconds. Default: 50
264
+ * @param config.onError (optional)
265
+ * @param config.leading (optional) if true, will enable leading-edge debounce mechanism.
266
+ * @param config.thisArg (optional) the special `thisArgs` to be used when invoking the callback.
267
+ * @param config.tid (optional) Timeout Id. If provided, will clear the timeout on first invocation.
268
+ *
269
+ * @example Debounce function calls
270
+ * ```typescript
271
+ * import { deferred } from '@superutils/core'
272
+ *
273
+ * const handleChange = deferred(
274
+ * event => console.log(event.target.value),
275
+ * 300 // debounce delay in milliseconds
276
+ * )
277
+ *
278
+ * handleChange({ target: { value 1 } }) // will be ignored
279
+ * handleChange({ target: { value 2 } }) // will be ingored
280
+ * handleChange({ target: { value 3 } }) // will be invoked
281
+ * ```
282
+ *
283
+ *
284
+ */
285
+ declare const deferred: {
286
+ <TArgs extends unknown[], ThisArg>(callback: (this: ThisArg, ...args: TArgs) => ValueOrPromise<unknown>, delay?: number, config?: DeferredConfig<ThisArg>): (...args: TArgs) => void;
287
+ defaults: {
288
+ /**
289
+ * Set the default value of argument `leading` for the `deferred` function.
290
+ * This change is applicable application-wide and only applies to any new invocation of `deferred()`.
291
+ */
292
+ leading: false;
293
+ /**
294
+ * Set the default value of argument `onError` for the `deferred` function.
295
+ * This change is applicable application-wide and only applies to any new invocation of `deferred()`.
296
+ */
297
+ onError: undefined;
298
+ };
299
+ };
300
+
301
+ /** Super for `deferred()` function */
302
+ declare function debounce(...args: Parameters<typeof deferred>): (...args: unknown[]) => void;
303
+
304
+ /**
305
+ * If `T` is a promise turn it into an union type by adding the value type
306
+ */
307
+ type IfPromiseAddValue<T> = T extends Promise<infer V> ? T | V : T;
308
+ /**
309
+ * @function fallbackIfFails
310
+ * @summary a flexible try-catch wrapper for invoking functions and ignore errors gracefully.
311
+ * Yes, the goal of `fallbackIfFails` is to ignore all runtime errors
312
+ * and ensure there's always a value returned.
313
+ *
314
+ * ---
315
+ *
316
+ * `fallbackValue` PS:
317
+ *
318
+ * 1. If function provided and Error is thrown it will not be caught.
319
+ * A fallback of the fallback is out of the scope of this function.
320
+ * 2. If `target` a promise or async function, `fallbackValue` must either be a promise or resolve to a promise
321
+ *
322
+ * ---
323
+ *
324
+ * @param target promise or function to execute
325
+ * @param args arguments to be supplied to `func` fuction
326
+ * @param fallbackValue alternative value to be used when target throws error.
327
+ *
328
+ * @returns if func is a promise the return a promise
329
+ *
330
+ * Examples:
331
+ * ---
332
+ * @example Async functions
333
+ * Working with async functions or functions that returns a promise
334
+ * ```typescript
335
+ * const args = ['some value', true] as const
336
+ * const ensureValue = async (value: string, criteria?: boolean) => {
337
+ * if (criteria !== false && !value.trim()) throw new Error('No value. Should use fallback value')
338
+ * return value
339
+ * }
340
+ * // This makes sure there's always a value without having to manually write try-catch block.
341
+ * const value = await fallbackIfFails(
342
+ * ensureValue,
343
+ * () => args,
344
+ * async () => 'fallback value'
345
+ * )
346
+ * ```
347
+ *
348
+ * @example Non-async functions
349
+ * Working synchronous function that returns value synchronously
350
+ * ```typescript
351
+ * const args = ['some value', true] as const
352
+ * const ensureValue = (value: string, criteria?: boolean) => {
353
+ * if (criteria !== false && !value.trim()) throw new Error('No value. Should use fallback value')
354
+ * return value
355
+ * }
356
+ * // this makes sure there's always a value without having to manually write try-catch block.
357
+ * const value = fallbackIfFails(
358
+ * ensureValue,
359
+ * () => args,
360
+ * () => 'fallback value'
361
+ * )
362
+ * ```
363
+ *
364
+ * @example Hybrid functions
365
+ * Working with function that returns value sync/async circumstantially
366
+ * ```typescript
367
+ * const getData = (useCache = true, cacheKey = 'data-cache') => {
368
+ * if (useCache && localStorage[cacheKey]) return localStorage[cacheKey]
369
+ * return fetch('https://my.domain.com/api')
370
+ * .then(r => r.json())
371
+ * .then(data => {
372
+ * if(cacheKey) localStorage[cacheKey] = data
373
+ * return data
374
+ * })
375
+ * }
376
+ * // First call: no cache, will execute fetch and return a promise
377
+ * const first = await fallbackIfFails(getData, [false], {})
378
+ * // Second call: cache available and will return data synchronously
379
+ * const second = fallbackIfFails(getData, [true], {})
380
+ * ```
381
+ */
382
+ declare const fallbackIfFails: <T, TArgs extends unknown[] = unknown[]>(target: T | ((...args: TArgs) => T), args: TArgs | (() => TArgs), fallbackValue: IfPromiseAddValue<T> | ((reason: unknown) => IfPromiseAddValue<T>)) => T;
383
+
384
+ /** Cast a value as `any` type to bypass type check. Use with caution. */
385
+ declare const asAny: <T = any>(x: unknown) => T;
386
+ /** Force cast one type into another to bypass type checks. Use with caution. */
387
+ declare const forceCast: <T>(x: unknown) => T;
388
+
389
+ /** Check if value is an array */
390
+ declare const isArr: <Item = unknown>(x: unknown) => x is Item[];
391
+ /**
392
+ * Check if value is an array of objects
393
+ */
394
+ declare const isArrObj: <K extends PropertyKey, V, T extends Record<K, V>[]>(x: unknown, strict?: boolean) => x is T[];
395
+ /** Check if argument is a 2-dimentional array */
396
+ declare const isArr2D: <Item = unknown>(x: unknown) => x is Item[][];
397
+ /** Check if value is convertible to an array by using `Array.from(x)` */
398
+ declare const isArrLike: (x: any) => x is typeof x extends (infer Value)[] ? Value[] : typeof x extends Set<infer Value> ? Set<Value> : typeof x extends Map<infer Key, infer Value> ? Map<Key, Value> : never;
399
+ /**
400
+ * Check if value is convertible to an array by using `Array.from(x)` even if it comes from a different realm
401
+ * (eg: iframe, iframes, worker contexts, node vm contexts, browser extensions).
402
+ *
403
+ * Caution: much slower than {@link isArrLike()} due to use of `Object.prototype.toString.call()`
404
+ */
405
+ declare const isArrLikeSafe: <T = unknown, MapKey = unknown>(x: unknown) => x is Set<T> | Map<MapKey, T> | T[];
406
+ /** Check if all values in the array are unique */
407
+ declare const isArrUnique: <T = unknown>(arr: T[]) => boolean;
408
+ /** Check if value is instance of Uint8Array */
409
+ declare const isUint8Arr: (arr: unknown) => arr is Uint8Array<ArrayBufferLike>;
410
+
411
+ /** Check if value is instance of Date */
412
+ declare const isDate: (x: unknown) => x is Date;
413
+ /**
414
+ * Check if a value is a valid date.
415
+ *
416
+ * @param date The value to check. Can be a Date object or a string.
417
+ *
418
+ * @returns `true` if the value is a valid date, `false` otherwise.
419
+ */
420
+ declare const isDateValid: (date: unknown) => boolean;
421
+
422
+ /**
423
+ * Check if variable contains empty, null-ish value.
424
+ *
425
+ * Depending on the type certain criteria applies:
426
+ * - `null` | `undefined`: always empty
427
+ * - `String`: empty text or only white-spaces
428
+ * - `Number`: non-finite or NaN
429
+ * - `Array` | `Uint8Array` | `Map` | `Set` | `Object`: contains zero items/properties
430
+ * - `Boolean` | `Function` | `Symbol` | `BigInt`: never empty
431
+ *
432
+ * @param x The value to check for emptiness.
433
+ * @param nonNumerable (optional) when `true`, considers non-enumerable properties
434
+ * while checking objects for emptiness. Default: `false`
435
+ * @param fallback (optional) value to return when type is unrecognized.
436
+ * Default: `false`
437
+ *
438
+ * @example Check strings
439
+ * ```typescript
440
+ * import { isEmpty } from '@superutils/core'
441
+ * isEmpty('') // true
442
+ * isEmpty(' ') // true
443
+ * isEmpty(`
444
+ *
445
+ *
446
+ * `) // true
447
+ * isEmpty(' not empty ') // false
448
+ * isEmpty(`
449
+ *
450
+ * not empty
451
+ *
452
+ * `) // false
453
+ * ```
454
+ *
455
+ * @example check numbers
456
+ * ```typescript
457
+ * import { isEmpty } from '@superutils/core'
458
+ * isEmpty(NaN) // true
459
+ * isEmpty(Infinity) // true
460
+ * isEmpty(0) // false
461
+ * ```
462
+ *
463
+ *
464
+ * @example check objects (includes arrays, maps & sets)
465
+ * ```typescript
466
+ * import { isEmpty } from '@superutils/core'
467
+ * isEmpty({}) // true
468
+ * isEmpty([]) // true
469
+ * isEmpty(new Map()) // true
470
+ * isEmpty(new Set()) // true
471
+ * ```
472
+ */
473
+ declare const isEmpty: (x: unknown, nonNumerable?: boolean, fallback?: boolean | 0 | 1) => boolean | 0 | 1;
474
+ /**
475
+ * Safe version of {@link isEmpty} with extended type checks and cross-realm handling.
476
+ *
477
+ * CAUTION: much slower than {@link isEmpty} due to use of Object.prototype.toString.call()
478
+ *
479
+ * Cross-realm means objects created in different JavaScript contexts.
480
+ * Eg: iframe, node vm context, worker context, browser extensions etc.
481
+ *
482
+ *
483
+ * @param x The value to check for emptiness.
484
+ *
485
+ * @returns `true` if the value is considered empty, `false` otherwise.
486
+ */
487
+ declare const isEmptySafe: (x: unknown, numberableOnly?: boolean) => boolean | 1;
488
+
489
+ /** Check if the environment is Browser */
490
+ declare const isEnvBrowser: () => boolean;
491
+ /** Check if the environment is NodeJS */
492
+ declare const isEnvNode: () => boolean;
493
+ /** Check if page is loaded on a touchscreen device */
494
+ declare const isEnvTouchable: () => boolean;
495
+
496
+ /** Check if value is a function */
497
+ declare const isFn: <T extends (...args: any[]) => any>(x: unknown) => x is T;
498
+ /**
499
+ * Check if value is an Async function.
500
+ * Caution: May not work at runtime when Babel/Webpack is used due to code compilation.
501
+ *
502
+ * ---
503
+ * @example usage
504
+ * ```typescript
505
+ * isAsyncFn(async () => {}) // result: true
506
+ * isAsyncFn(() => {}) // result: false
507
+ * ```
508
+ */
509
+ declare const isAsyncFn: <TData = unknown, TArgs extends unknown[] = unknown[]>(x: unknown) => x is AsyncFn<TData, TArgs>;
510
+
511
+ /** Check if value is instance of Map */
512
+ declare const isMap: <TKey = unknown, TValue = unknown>(x: unknown) => x is Map<TKey, TValue>;
513
+ /** Check if provided is a Map and all values are objects */
514
+ declare const isMapObj: <K extends PropertyKey, V, T extends Record<K, V>>(x: unknown, strict?: boolean) => x is Map<K, V>;
515
+
516
+ /** Check if value is an integer */
517
+ declare const isInteger: (x: unknown) => x is number;
518
+ /** Check if value is a positive integer */
519
+ declare const isPositiveInteger: (x: unknown) => x is number;
520
+ /** Check if value is a positive number */
521
+ declare const isPositiveNumber: (x: unknown) => x is number;
522
+ /** Check if value is a valid finite number */
523
+ declare const isNumber: (x: unknown) => x is number;
524
+
525
+ /**
526
+ * Check if value is an object.
527
+ *
528
+ *
529
+ * @param x value to check
530
+ * @param strict (optional) whether to exclude anything other than plain object. Eg: Array, Map, RegExp, Set etc.
531
+ *
532
+ * Default: `true`
533
+ *
534
+ * Valid objects:
535
+ * - object literals (Prototype: `Object.prototype`)
536
+ * - objects created using `Object.create(null)`
537
+ *
538
+ * Valid when strict mode off (false):
539
+ * - all of above
540
+ * - buit-in objects like Date, Error, Map, Set, Uint8Array etc
541
+ * - custom Class instances
542
+ * - objects created using `Object.create(object)`
543
+ *
544
+ * Always invalid:
545
+ * - `null`, `undefined`, `NaN`, `Infinity`
546
+ * - primitive: String, Number, BigInt...
547
+ *
548
+ * @example Examples
549
+ * ```typescript
550
+ * import { isObj } from '@superutils/core'
551
+ *
552
+ * console.log(isObj(null)) // false
553
+ * console.log(isObj(undefined)) // false
554
+ * console.log(isObj(NaN)) // false
555
+ * console.log(isObj(Infinity)) // false
556
+ * console.log(isObj({})) // true
557
+ * console.log(isObj({ a: 1, b: 2})) // true
558
+ * console.log(isObj(Object.create(null))) // true
559
+ * console.log(isObj(new Map())) // false (strict)
560
+ * console.log(isObj(new Map(), false)) // true (non-strict)
561
+ * console.log(isObj(new Error('error'))) // false (strict)
562
+ * console.log(isObj(new Error('error'), false)) // true (non-strict)
563
+ * class Test { a = 1 }) // a custom class
564
+ * console.log(isObj(new Test())) // false
565
+ * console.log(isObj(new Test(), false)) // true
566
+ * ```
567
+ */
568
+ declare const isObj: <T = Record<PropertyKey, unknown>>(x: unknown, strict?: boolean) => x is T;
569
+
570
+ /** Check if value is instance of URL */
571
+ declare const isUrl: (x: unknown) => x is URL;
572
+ /**
573
+ * Check if a value is a valid URL/string-URL.
574
+ *
575
+ * @param x The value to check.
576
+ * @param strict If true:
577
+ * - requires a domain name with a TLDs etc.
578
+ * - and x is string, catches any auto-correction (eg: trailing spaces being removed, spaces being replaced by `%20`)
579
+ * by `new URL()` to ensure string URL is valid
580
+ * Defaults to `true`.
581
+ * @param tldExceptions when in strict mode, treat these hosts as valid despite no domain name extensions
582
+ * Defaults to `['localhost']`
583
+ *
584
+ * @returns `true` if the value is a valid URL, `false` otherwise.
585
+ */
586
+ declare const isUrlValid: (x: unknown, strict?: boolean, tldExceptions?: string[]) => boolean;
587
+
588
+ /** Check if value is boolean */
589
+ declare const isBool: (x: unknown) => x is boolean;
590
+ /** Check if value is not undefined or null */
591
+ declare const isDefined: <T = unknown>(x: T | undefined | null) => x is T;
592
+ /** Check if value is instance of Error */
593
+ declare const isError: (x: unknown) => x is Error;
594
+ /** Check if value is a Promise */
595
+ declare const isPromise: <T = unknown>(x: unknown) => x is Promise<T>;
596
+ /** Check if value is a regular expession */
597
+ declare const isRegExp: (x: unknown) => x is RegExp;
598
+ /** Check if value is instance of Set */
599
+ declare const isSet: <T = unknown>(x: unknown) => x is Set<T>;
600
+ /** Check if value is string */
601
+ declare const isStr: (x: unknown) => x is string;
602
+ /** Check if value is a Symbol */
603
+ declare const isSymbol: (x: unknown) => x is symbol;
604
+ /**
605
+ * Compilation of all the compile-time & runtime utilities functions above
606
+ */
607
+ declare const is: {
608
+ arr: <Item = unknown>(x: unknown) => x is Item[];
609
+ arr2D: <Item = unknown>(x: unknown) => x is Item[][];
610
+ arrLike: (x: any) => x is typeof x extends (infer Value)[] ? Value[] : typeof x extends Set<infer Value> ? Set<Value> : typeof x extends Map<infer Key, infer Value> ? Map<Key, Value> : never;
611
+ arrLikeSafe: <T = unknown, MapKey = unknown>(x: unknown) => x is Set<T> | Map<MapKey, T> | T[];
612
+ arrObj: <K extends PropertyKey, V, T extends Record<K, V>[]>(x: unknown, strict?: boolean) => x is T[];
613
+ arrUnique: <T = unknown>(arr: T[]) => boolean;
614
+ asyncFn: <TData = unknown, TArgs extends unknown[] = unknown[]>(x: unknown) => x is AsyncFn<TData, TArgs>;
615
+ bool: (x: unknown) => x is boolean;
616
+ date: (x: unknown) => x is Date;
617
+ dateValid: (date: unknown) => boolean;
618
+ defined: <T = unknown>(x: T | undefined | null) => x is T;
619
+ empty: (x: unknown, nonNumerable?: boolean, fallback?: boolean | 0 | 1) => boolean | 0 | 1;
620
+ emptySafe: (x: unknown, numberableOnly?: boolean) => boolean | 1;
621
+ envBrowser: () => boolean;
622
+ envNode: () => boolean;
623
+ envTouchable: () => boolean;
624
+ error: (x: unknown) => x is Error;
625
+ fn: <T extends (...args: any[]) => any>(x: unknown) => x is T;
626
+ integer: (x: unknown) => x is number;
627
+ map: <TKey = unknown, TValue = unknown>(x: unknown) => x is Map<TKey, TValue>;
628
+ mapObj: <K extends PropertyKey, V, T extends Record<K, V>>(x: unknown, strict?: boolean) => x is Map<K, V>;
629
+ number: (x: unknown) => x is number;
630
+ obj: <T = Record<PropertyKey, unknown>>(x: unknown, strict?: boolean) => x is T;
631
+ positiveInteger: (x: unknown) => x is number;
632
+ positiveNumber: (x: unknown) => x is number;
633
+ promise: <T = unknown>(x: unknown) => x is Promise<T>;
634
+ regExp: (x: unknown) => x is RegExp;
635
+ set: <T = unknown>(x: unknown) => x is Set<T>;
636
+ str: (x: unknown) => x is string;
637
+ symbol: (x: unknown) => x is symbol;
638
+ uint8Arr: (arr: unknown) => arr is Uint8Array<ArrayBufferLike>;
639
+ url: (x: unknown) => x is URL;
640
+ urlValid: (x: unknown, strict?: boolean, tldExceptions?: string[]) => boolean;
641
+ };
642
+
643
+ /** Placeholder function that does nothing */
644
+ declare function noop(): void;
645
+ declare function noopAsync(): Promise<void>;
646
+
647
+ type ThrottleConfig<ThisArg = unknown> = {
648
+ onError?: (err: unknown) => ValueOrPromise<unknown>;
649
+ thisArg?: ThisArg;
650
+ trailing?: boolean;
651
+ tid?: TimeoutId;
652
+ };
653
+ /**
654
+ * @function throttle
655
+ * @summary returns a function that invokes the `callback` maximum twice (once if `executeLast = false`) per interval
656
+ *
657
+ * @param callback function to be invoked after timeout
658
+ * @param delay (optional) interval duration in milliseconds. Default: 50
659
+ * @param config.onError (optional)
660
+ * @param config.tid (optional)
661
+ * @param config.thisArg (optional) the special `thisArgs` to be used when invoking the callback.
662
+ * @param config.trailing (optional) whether to enable trailing edge execution. Default: `true`
663
+ */
664
+ declare const throttled: {
665
+ <TArgs extends unknown[], ThisArg>(callback: (this: ThisArg, ...args: TArgs) => ValueOrPromise<unknown>, delay?: number, config?: ThrottleConfig<ThisArg>): (...args: TArgs) => void;
666
+ /**
667
+ * Set the default values
668
+ * This change is applicable application-wide and only applies to any new invocation of `throttle()`.
669
+ */
670
+ defaults: {
671
+ onError: undefined;
672
+ trailing: true;
673
+ };
674
+ };
675
+
676
+ /**
677
+ * Convert timestamp to `input["datetime-local"]` compatible format.
678
+ *
679
+ * ---
680
+ * @example Convert ISO datetime string
681
+ * ```typescript
682
+ * toDatetimeLocal('2000-01-01T01:01:01.001Z')
683
+ * // result: "2000-01-01T01:01" // assuming local timezone is UTC+0
684
+ * ```
685
+ *
686
+ * @example Convert Date object
687
+ * ```typescript
688
+ * const date = new Date('2000-01-01T01:01:01.001Z')
689
+ * toDatetimeLocal(date)
690
+ * // result: "2000-01-01T01:01" // assuming local timezone is UTC+0
691
+ * ```
692
+ *
693
+ * @example Convert Unix Timestamp (epoch time) number
694
+ * ```typescript
695
+ * const epoch = new Date('2000-01-01T01:01:01.001Z').getTime()
696
+ * toDatetimeLocal(epoch)
697
+ * // result: "2000-01-01T01:01" // assuming local timezone is UTC+0
698
+ * ```
699
+ */
700
+ declare const toDatetimeLocal: (dateStr: string | Date | number) => "" | `${number}-${number}-${number}T${number}:${number}`;
701
+
702
+ /**
703
+ * Constructs a new object with only the supplied property names (keys) and their respective values
704
+ *
705
+ * @param obj
706
+ * @param keys property names to keep
707
+ * @param ignoreIfNotExist (optional) if truthy, will ignore non-existent `keys`. Default: `true`
708
+ */
709
+ declare const objClean: <T extends Record<PropertyKey, unknown>, Key extends keyof T = keyof T>(obj: T, keys: Key[], ignoreIfNotExist?: boolean) => Record<Key, T[Key]>;
710
+
711
+ /**
712
+ * Deep-copy an object to another object
713
+ *
714
+ * @param input input object
715
+ * @param ignoreKeys (optional) input peroperties to be ignored. Prevents output's property to be overriden.
716
+ *
717
+ * For child object properties use "." (dot) separated path.
718
+ *
719
+ * Eg: `"child.grandchild1"` where input is `{ child: { grandchild1: 1, grandchild2: 2 }}`
720
+ *
721
+ * @param output (optional) output object
722
+ * @param override (optional) whether to allow override output (if provided) properties.
723
+ * Accepted values:
724
+ * `true`: input property will override output property
725
+ * `false`: no overriding if output contains the property. Even if the property value is `undefined`.
726
+ * `"empty"`: only allow overriding output property if it's value is empty by using {@link isEmpty}.
727
+ *
728
+ * Default: `false`
729
+ *
730
+ *
731
+ * @returns copied and/or merged object
732
+ */
733
+ declare const objCopy: <Key extends string | symbol, T extends Record<Key, unknown>, IgnoredKey extends Key | string>(input: T, output?: Record<PropertyKey, unknown>, ignoreKeys?: IgnoredKey[] | Set<IgnoredKey>, override?: boolean | "empty", recursive?: boolean) => Record<PropertyKey, unknown>;
734
+
735
+ /**
736
+ * Creates an object from an array of keys and a corresponding array of values.
737
+ * It pairs each key with the value at the same index.
738
+ *
739
+ * @param keys An array of property keys (strings or symbols).
740
+ * @param values (optional) An array of property values. The value at each index corresponds to the key at the same index. If a value is missing for a key, it will be `undefined`.
741
+ * @param result (optional) An existing object to add or overwrite properties on. If not provided, a new object is created.
742
+ * @returns The newly created object, or the `result` object merged with the new properties.
743
+ *
744
+ * @example Creating a new object from keys and values
745
+ * ```typescript
746
+ * const keys = ['a', 'b', 'c'];
747
+ * const values = [1, 2, 3];
748
+ * const newObj = objCreate(keys, values);
749
+ * // newObj is { a: 1, b: 2, c: 3 }
750
+ * ```
751
+ *
752
+ * @example Merging into an existing object
753
+ * ```typescript
754
+ * const existingObj = { a: 0, d: 4 };
755
+ * const keys = ['b', 'c'];
756
+ * const values = [2, 3];
757
+ * objCreate(keys, values, existingObj);
758
+ * // existingObj is now { a: 0, d: 4, b: 2, c: 3 }
759
+ * ```
760
+ */
761
+ declare const objCreate: <V, K extends PropertyKey, RV, RK extends PropertyKey, Result extends Record<K | RK, V | RV>>(keys?: K[], values?: V[], result?: Result) => Result;
762
+
763
+ /**
764
+ * Get object property names/keys
765
+ *
766
+ * @param obj target object
767
+ * @param sorted (optional) Whether to sort the keys. Default: `true`
768
+ * @param includeSymbols (optional) Whether to include `Symbol` object. Default: `false`
769
+ */
770
+ declare const objKeys: <T extends object, Include extends true | false = true>(obj: T, sorted?: boolean, includeSymbols?: Include) => Include extends true ? (keyof T)[] : (keyof T)[] & string[];
771
+
772
+ type ReadOnlyAllowAddFn<T> = (obj: T, key: string | symbol, valule: unknown) => boolean;
773
+ type ReadOnlyConfig<T, Revocable extends true | false = false> = {
774
+ /** Whether to allow adding new properties. Default: `false` */
775
+ add?: boolean | ReadOnlyAllowAddFn<T>;
776
+ /** Default: `false` */
777
+ revocable?: Revocable;
778
+ /** Whether to throw error when a write operation is rejected. Default: `true` */
779
+ silent?: boolean;
780
+ };
781
+
782
+ /**
783
+ * Constructs a new read-only object where only new properties can be added.
784
+ *
785
+ * Applies only to the top-level properties.
786
+ *
787
+ * @param obj input object
788
+ * @param config (optional) extra configuration
789
+ * @param config.add (optional) Whether to allow adding new properties. Default: `false`
790
+ * @param config.revocable (optional) Whether to create a revokable proxy. Default: `false`
791
+ * @param config.silent (optional) whether to throw error when a write operation is rejected. Default: `false`
792
+ *
793
+ * @returns Readonly object or object containing readonly object and revoke function
794
+ */
795
+ declare const objReadOnly: <T extends object | unknown[], Revocable extends true | false = false, Result = Revocable extends true ? ReturnType<typeof Proxy.revocable<T>> : T>(obj: T, config?: ReadOnlyConfig<T, Revocable>) => Result;
796
+
797
+ /**
798
+ * Assign value to an object property
799
+ *
800
+ * @param obj
801
+ * @param key
802
+ * @param falsyValue (optional) Default: `obj[key]`
803
+ * @param condition (optional)
804
+ * @param truthyValue (optional) value to use if condition is truthy
805
+ */
806
+ declare const objSetProp: <K extends PropertyKey, V, OutKey extends K | string>(obj: Record<K, V>, key: OutKey, falsyValue?: V, condition?: boolean | ((value: V | undefined, key: OutKey, obj: Record<K, V>) => boolean), truthyValue?: V) => Record<OutKey, V>;
807
+ /** Assign value to an object property only if current value is undefined */
808
+ declare const objSetPropUndefined: (...[obj, key, ...args]: Parameters<typeof objSetProp>) => Record<PropertyKey, unknown>;
809
+
810
+ /** create a new object with properties sorted by key */
811
+ declare const objSort: <T>(obj: T, recursive?: boolean, _done?: Map<unknown, boolean>) => T;
812
+
813
+ /**
814
+ * @function objWithoutKeys
815
+ * @summary constructs a new object excluding specific properties
816
+ *
817
+ * @param {Object} input
818
+ * @param {Array} keys property names to exclude
819
+ * @param {Object} output (optional) to delete unwanted props from the original `input` use it here.
820
+ * Default: a copy of the `input` object
821
+ *
822
+ * @returns {Object}
823
+ */
824
+ declare const objWithoutKeys: (input: unknown, keys: string[], output?: Record<PropertyKey, unknown>) => Record<PropertyKey, unknown>;
825
+
826
+ /**
827
+ * Sugar for `objReadOnly()` for an Array
828
+ *
829
+ * @param arr
830
+ * @param config (optional)
831
+ * @param config.add (optional) Whether to allow adding new properties. Default: `false`
832
+ * @param config.revocable (optional) Default: `false`
833
+ * @param config.silent (optional) Whether to throw error when a write operation is rejected. Default: `true`
834
+ *
835
+ * @returns Readonly Array or object containing readonly Array and revoke function
836
+ */
837
+ declare const arrReadOnly: <T>(arr: T[], config?: Omit<ReadOnlyConfig<T[]>, "revoke">) => T[];
838
+
839
+ /**
840
+ * Helper class for creating read-only arrays.
841
+ *
842
+ * Caution: This class can by itself only make the array partially read-only.
843
+ * Use {@link arrReadOnly()} instead.
844
+ */
845
+ declare class ReadOnlyArrayHelper<T> extends Array<T> {
846
+ readonly config: Omit<ReadOnlyConfig<T[]>, 'revoke'>;
847
+ constructor(config: Omit<ReadOnlyConfig<T[]>, 'revoke'>, arr: T[]);
848
+ private ignoreOrThrow;
849
+ pop: () => T;
850
+ push: (...items: T[]) => number;
851
+ reverse: () => this;
852
+ shift: () => T;
853
+ splice: (..._ignoredArgs: unknown[]) => never[];
854
+ unshift: (..._ignoredArgs: T[]) => number;
855
+ reduce: {
856
+ (callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
857
+ (callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
858
+ <U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
859
+ };
860
+ reduceRight: {
861
+ (callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
862
+ (callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
863
+ <U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
864
+ };
865
+ }
866
+
867
+ /**
868
+ * Reverse an array conditionally
869
+ *
870
+ * @param arr
871
+ * @param reverse (optional) condition to reverse the array. Default: `true`
872
+ * @param newArray (optional) whether to cnstruct new array or use input. Default: `false`
873
+ *
874
+ * @returns array
875
+ */
876
+ declare const arrReverse: <T = unknown>(arr: T[], reverse?: boolean, newArray?: boolean) => T[];
877
+
878
+ /**
879
+ * Generate a Map from one or more arrays
880
+ *
881
+ * @param arr
882
+ * @param key (optional) Array object-item property name or a function to generate keys for each array items.
883
+ * @param flatDepth (optional) maximum recursion depth to flatten the array. Default: `0`
884
+ *
885
+ * @returns Converted Map
886
+ *
887
+ * @example Convert Array to Map
888
+ * ```typescript
889
+ * type Item = { a: number }
890
+ * const arr: Item[] = [{ a: 1 }, { a: 2 }, { a: 3 }, [{ a: 4 }]]
891
+ * const map: Map<number, Item> = arrToMap(
892
+ * arr,
893
+ * (_: Item, i: number) => item.a,
894
+ * )
895
+ *
896
+ * @example Flatten and convert Array to Map
897
+ * ```typescript
898
+ * type Item = { key: number; value: string }
899
+ * const arr: (Item | Item[])[] = [
900
+ * { key: 1, value: 'a' },
901
+ * { key: 2, value: 'b' },
902
+ * { key: 3, value: 'c' },
903
+ * [{ key: 4, value: 'd' }],
904
+ * ]
905
+ * const map = arrToMap(arr, (item: Item) => item.key, 1) // Map<number, Item>
906
+ * ```
907
+ */
908
+ declare function arrToMap<T extends unknown[], FlatDepth extends number = 0>(arr: T, flatDepth?: FlatDepth): Map<number, FlatArray<T, FlatDepth>>;
909
+ declare function arrToMap<T extends unknown[], FlatDepth extends number = 0, MapItem = FlatArray<T, FlatDepth>, MapKey = unknown>(arr: T, key: (item: MapItem, index: number, flatArr: MapItem[]) => MapKey, flatDepth?: FlatDepth): Map<MapKey, MapItem>;
910
+ declare function arrToMap<T extends unknown[], FlatDepth extends number = 0, MapItem = FlatArray<T, FlatDepth>, KeyProp extends keyof MapItem = keyof MapItem>(arr: T, key: KeyProp, flatDepth?: FlatDepth): Map<MapItem[KeyProp], MapItem>;
911
+
912
+ /**
913
+ * @function arrUnique
914
+ * @summary constructs a new array of unique values
915
+ */
916
+ declare const arrUnique: <T = unknown>(arr: T[], flatDepth?: number) => FlatArray<T, 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -1 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20>[];
917
+
918
+ /** Configuration for finding {@link IterableList} items */
919
+ type FindOptions<K, V, IncludeKey extends boolean = false> = Omit<SearchOptions<K, V>, 'limit' | 'asMap'> & {
920
+ /**
921
+ * Whether to include the key in the return type.
922
+ *
923
+ * If `true`, return type is `[K, V]` else `V`
924
+ *
925
+ * Default: `false`
926
+ */
927
+ includeKey?: IncludeKey;
928
+ };
929
+ /** A general type to capture all iterables like Array, Map, Set.... */
930
+ type IterableList<K = unknown, V = unknown> = {
931
+ entries: () => IterableIterator<[K, V]>;
932
+ hasOwnProperty: (name: string) => boolean;
933
+ keys: () => IterableIterator<K>;
934
+ values: () => IterableIterator<V>;
935
+ } & ({
936
+ clear: () => void;
937
+ size: number;
938
+ } | {
939
+ length: number;
940
+ });
941
+ /** Configuration for sorting iterables */
942
+ type SortOptions = {
943
+ ignoreCase?: boolean;
944
+ /**
945
+ * Whether to create a new instance of preserve original reference
946
+ *
947
+ * Default: `true` for Array, `false` for Map.
948
+ */
949
+ newInstance?: boolean;
950
+ /** Reverse sorted result */
951
+ reverse?: boolean;
952
+ /**
953
+ * Whether to place undefined/null values at the beginning of the sorted array.
954
+ *
955
+ * Default: `false`
956
+ */
957
+ undefinedFirst?: boolean;
958
+ };
959
+ /** Search criteria for searcheing iterables */
960
+ type SearchOptions<K, V, AsMap extends boolean = false> = {
961
+ /** Whethere to return the result as a map (`true`) or array (`false`). Default: `true` */
962
+ asMap?: AsMap;
963
+ /** case-insensitive search for strings. Default: `false` */
964
+ ignoreCase?: boolean;
965
+ /** limit number of results. Default: `Infinity` */
966
+ limit?: number;
967
+ /** partial match for values. Default: `false` */
968
+ matchExact?: boolean;
969
+ /** match all supplied key-value pairs. Default: `false` */
970
+ matchAll?: boolean;
971
+ /** key-value pairs */
972
+ query: Record<string, unknown> | string | RegExp;
973
+ /** Map to store results in. Default: `new Map()` */
974
+ result?: Map<K, V>;
975
+ /** Callback to convert item/item-property to string */
976
+ transform?: (
977
+ /** List item */
978
+ item: V,
979
+ /** Item property value or `undefined` for fuzzy search. */
980
+ value?: V[keyof V],
981
+ /** Item property key provided by query or `undefined` for fuzzy search. */
982
+ key?: keyof V) => string | undefined;
983
+ };
984
+
985
+ /**
986
+ * Filter {@link IterableList} (Array, Map, Set) items.
987
+ *
988
+ * @param data
989
+ * @param predicate callback function to filter values
990
+ *
991
+ * @returns new Map with filtered items
992
+ *
993
+ * @example
994
+ * ```typescript
995
+ * import { filter } from '@superutils/core'
996
+ *
997
+ * const map = new Map<number, { name: string; age: number }>([
998
+ * [1, { name: 'Alice', age: 30 }],
999
+ * [2, { name: 'Bob', age: 25 }],
1000
+ * [3, { name: 'Charlie', age: 35 }],
1001
+ * ])
1002
+ *
1003
+ * const filtered = filter(map, item => item.age >= 30)
1004
+ * // result: Map(2) {
1005
+ * // 1 => { name: 'Alice', age: 30 },
1006
+ * // 3 => { name: 'Charlie', age: 35 }
1007
+ * // }
1008
+ * ```
1009
+ */
1010
+ declare const filter: <K, V, AsArray extends boolean = false, Result = AsArray extends true ? V[] : Map<K, V>>(data: IterableList<K, V>, predicate: (value: V, key: K, data: IterableList<K, V>) => boolean, limit?: number, asArray?: AsArray, result?: Map<K, V>) => Result;
1011
+
1012
+ /**
1013
+ * Finds a first item matching criteria in an {@link IterableList}.
1014
+ *
1015
+ * @returns first item matched or `undefined` if not found
1016
+ *
1017
+ * @example Find item using callback
1018
+ * ```typescript
1019
+ * import { find } from '@superutils/core'
1020
+ *
1021
+ * const map = new Map<number, { name: string; age: number }>([
1022
+ * [1, { name: 'Alice', age: 30 }],
1023
+ * [2, { name: 'Bob', age: 25 }],
1024
+ * [3, { name: 'Charlie', age: 35 }],
1025
+ * ])
1026
+ * const result = mapFind(testMap, ({ name }) => name === 'Bob')
1027
+ * // result: { name: 'Bob', age: 25 }
1028
+ * ```
1029
+ *
1030
+ * @example Find item using search options
1031
+ * ```typescript
1032
+ * import { find } from '@superutils/core'
1033
+ *
1034
+ * const map = new Map<number, { name: string; age: number }>([
1035
+ * [1, { name: 'Alice', age: 30 }],
1036
+ * [2, { name: 'Bob', age: 25 }],
1037
+ * [3, { name: 'Charlie', age: 35 }],
1038
+ * ])
1039
+ * const result = mapFind(testmap, {
1040
+ * query: 'Bob',
1041
+ * key: 'name',
1042
+ * })
1043
+ * // result: { name: 'Bob', age: 25 }
1044
+ * ```
1045
+ */
1046
+ declare function find<K, V extends Record<string, unknown>, IncludeKey extends boolean = false, Return = undefined | (IncludeKey extends true ? [K, V] : V)>(data: IterableList<K, V>, callback: Parameters<typeof filter<K, V>>[1]): Return;
1047
+ declare function find<K, V extends Record<string, unknown>, IncludeKey extends boolean = false, Return = undefined | (IncludeKey extends true ? [K, V] : V)>(data: IterableList<K, V>, options: FindOptions<K, V, IncludeKey>): Return;
1048
+
1049
+ /** Map entries as array */
1050
+ declare const getEntries: <K, V>(map: Map<K, V>) => [K, V][];
1051
+
1052
+ /** Get {@link IterableList} keys as array */
1053
+ declare const getKeys: <K, V>(data: IterableList<K, V>) => K[];
1054
+
1055
+ /** Get size/length of Array/Map/Set */
1056
+ declare const getSize: (x: IterableList) => number;
1057
+
1058
+ /** Get Map values as Array */
1059
+ declare const getValues: <K, V>(data: IterableList<K, V>) => V[];
1060
+
1061
+ /**
1062
+ * Reverse a {@link IterableList} (Array/Map/Set) conditionally
1063
+ *
1064
+ * @param data
1065
+ * @param reverse (optional) condition to reverse the list. Default: `true`
1066
+ * @param newInstance (optional) whether to return a new instance of the list. Default: `false`
1067
+ *
1068
+ * @returns reversed data in original type or empty array for unsupported type
1069
+ */
1070
+ declare const reverse: <K, V, T extends IterableList<K, V>>(data: T, reverse?: boolean, newInstance?: boolean) => V[] | [K, V][] | Map<K, V> | Set<V> | (T & Record<"clear", unknown>);
1071
+
1072
+ /**
1073
+ * A versatile utility for searching through an iterable list (e.g., Array, Map, Set) of objects.
1074
+ * It supports both a simple "fuzzy" search with a string query across all properties and a
1075
+ * detailed, field-specific search using a query object.
1076
+ *
1077
+ * @param data The list of objects to search within. Compatible types include:
1078
+ * - `Array`
1079
+ * - `Map`
1080
+ * - `Set`
1081
+ * - `NodeList` (in DOM environments): `options.transform()` required
1082
+ * - `HTMLCollection` (in DOM environments): should accompany `options.transform()`
1083
+ * @param options The search criteria.
1084
+ * @param options.query The search query. Can be a string to search all fields, or an object for field-specific
1085
+ * searches (e.g., `{ name: 'John', city: 'New York' }`).
1086
+ * @param options.asMap (optional) If `true`, returns a `Map`. If `false`, returns an `Array`. Default: `true`.
1087
+ * @param options.ignoreCase (optional) If `true`, performs a case-insensitive search for strings. Default: `true`.
1088
+ * @param options.limit (optional) The maximum number of results to return. Default: `Infinity`.
1089
+ * @param options.matchAll (optional) If `true`, an item must match all key-value pairs in the `query` object. If
1090
+ * `false`, it matches if at least one pair is found. Default: `false`.
1091
+ * @param options.matchExact (optional) If `true`, performs an exact match. If `false`, performs a partial match
1092
+ * (i.e., `includes()`). Default: `false`.
1093
+ * @param options.result (optional) An optional `Map` to which the results will be added.
1094
+ * @param options.transform (optional) Callback to transform item/item-property to string
1095
+ *
1096
+ * @returns A `Map` or an `Array` containing the matched items, based on the `asMap` option.
1097
+ *
1098
+ * @example
1099
+ * ```typescript
1100
+ * const users = [
1101
+ * { id: 1, name: 'John Doe', city: 'New York' },
1102
+ * { id: 2, name: 'Jane Doe', city: 'London' },
1103
+ * { id: 3, name: 'Peter Jones', city: 'New York' },
1104
+ * ];
1105
+ *
1106
+ * // Simple string search (case-insensitive, partial match by default)
1107
+ * const doeUsers = search(users, { query: 'doe' });
1108
+ * // Returns: [{ id: 1, ... }, { id: 2, ... }]
1109
+ *
1110
+ * // Field-specific search, requiring all fields to match
1111
+ * const peterInNY = search(users, {
1112
+ * query: { name: 'Peter', city: 'New York' },
1113
+ * matchAll: true,
1114
+ * });
1115
+ * // Returns: [{ id: 3, ... }]
1116
+ * ```
1117
+ */
1118
+ declare const search: {
1119
+ <K, V, AsMap extends boolean = true, Result = AsMap extends true ? Map<K, V> : V[]>(data: IterableList<K, V>, options: SearchOptions<K, V, AsMap>): Result;
1120
+ defaultOptions: Pick<Required<SearchOptions<unknown, unknown, true>>, "matchAll" | "limit" | "asMap" | "ignoreCase" | "matchExact">;
1121
+ };
1122
+ /** Utility for use with {@link search()} function */
1123
+ declare function matchItemOrProp<K, V>(// extends Record<string, unknown>
1124
+ { query, ignoreCase, matchExact, transform, }: Pick<SearchOptions<K, V, boolean>, 'transform' | 'query' | 'ignoreCase' | 'matchExact'>, item: V, propertyName?: string): boolean;
1125
+
1126
+ type SliceMapCallback<Data, Value, Key> = (item: Value, key: Key, data: Data) => Value;
1127
+ type SliceMapOptions<Data, Value, Key, AsMap extends boolean = false> = {
1128
+ /** Whether to return the result as a Map (preserving original keys) or an Array */
1129
+ asMap?: AsMap;
1130
+ /** callback to transform each item */
1131
+ transform?: SliceMapCallback<Data, Value, Key>;
1132
+ /** End index (exclusive). Default: `undefined` (end of the list) */
1133
+ end?: number;
1134
+ /** Whether to exclude item if value is `undefined | null` */
1135
+ ignoreEmpty?: boolean;
1136
+ /** Start index. Default: `0` */
1137
+ start?: number;
1138
+ };
1139
+ /**
1140
+ * Slice an iterable list and map the values into an Array/Map
1141
+ *
1142
+ * @param data Array, Map, Set...
1143
+ * @param start Default: `0`
1144
+ * @param end (optional) last index - exclusive. Default: index of the last item
1145
+ * @param callback to be executed on each item within the set range.
1146
+ *
1147
+ * If callback throws error or returnes `undefined`, the item will be ignored.
1148
+ *
1149
+ * Callback Params:
1150
+ * - item: current item
1151
+ * - key: index/key of the current item
1152
+ * - data: original list
1153
+ *
1154
+ * @returns Array/Map
1155
+ */
1156
+ declare const sliceMap: <Data extends IterableList, Key = Data extends IterableList<infer Key_1, unknown> ? Key_1 : never, Value = Data extends IterableList<unknown, infer Value_1> ? Value_1 : never, AsMap extends boolean = false>(data: Data, options?: SliceMapOptions<Data, Value, Key, AsMap> | SliceMapCallback<Data, Value, Key>) => AsMap extends false ? Value[] : Map<Key, Value>;
1157
+
1158
+ type EntryComparator<K, V> = (a: [K, V], b: [K, V]) => number;
1159
+ type ArrayComparator<V> = (a: V, b: V) => number;
1160
+ /**
1161
+ * Sort iterable lists (Array/Map/Set).
1162
+ *
1163
+ *
1164
+ * @param data
1165
+ * @param propertyName Accepted values:
1166
+ * - `string`: value object property name
1167
+ * - `function`: comparator function. Recommended for performance.
1168
+ * - `true`: indicates to sort by Map keys instead of values.
1169
+ * @param options (optional) extra sorting opitons
1170
+ * @param options.ignoreCase (optional) case-insensitive sort for strings. Default: `true`
1171
+ * @param options.reverse (optional) True: accending sort. False: descending sort. Default: `false`
1172
+ * @param options.undefinedFirst (optional) Where to place undefined/null values.
1173
+ * Not avaible when `comparator` function is used.
1174
+ * - `true`: at the beginning
1175
+ * - `false`: at the end
1176
+ *
1177
+ * Default: `false`
1178
+ *
1179
+ * @returns sorted map
1180
+ *
1181
+ * @example sort map of simple values (string/number/boolean)
1182
+ * ```typescript
1183
+ * import { sort } from '@superutils/core'
1184
+ * const map = new Map([
1185
+ * [1, 1],
1186
+ * [2, 2],
1187
+ * [0, 0],
1188
+ * ])
1189
+ * sort(map)
1190
+ * // result: Map(3) { 0 => 0, 1 => 1, 2 => 2 }
1191
+ * ```
1192
+ *
1193
+ * @example sort map of objects
1194
+ * ```typescript
1195
+ * import { sort } from '@superutils/core'
1196
+ * const map = new Map([
1197
+ * [0, { name: 'Charlie' }],
1198
+ * [1, { name: 'Alice' }],
1199
+ * [2, { name: 'Bob' }],
1200
+ * ])
1201
+ * sort(map, 'name')
1202
+ * // result: Map(3) {
1203
+ * // 1 => { name: 'Alice' },
1204
+ * // 2 => { name: 'Bob' },
1205
+ * // 0 => { name: 'Charlie' }
1206
+ * // }
1207
+ * ```
1208
+ */
1209
+ declare function sort<K, V extends Record<PropertyKey, unknown>, T extends IterableList<K, V>>(data: T, propertyName: keyof V & string, options?: SortOptions): T;
1210
+ /** Sort `Map` by map-keys `K` */
1211
+ declare function sort<K, V>(data: Map<K, V>, byKey: true, options?: SortOptions): Map<K, V>;
1212
+ /** Sort `Map` with comparator function */
1213
+ declare function sort<K, V>(map: Map<K, V>, comparator: EntryComparator<K, V>, options?: SortOptions): Map<K, V>;
1214
+ /** Sort `Array` with comparator function */
1215
+ declare function sort<V>(array: V[], comparator: ArrayComparator<V>, options?: SortOptions): V[];
1216
+ /** Sort `Set` with comparator function */
1217
+ declare function sort<V>(set: Set<V>, comparator: ArrayComparator<V>, options?: SortOptions): Set<V>;
1218
+ /** Sort Array/Map/Set with `string | boolean | number` values */
1219
+ declare function sort<K, V extends string | boolean | number, T extends IterableList<K, V>>(data: T, options?: SortOptions): T;
1220
+ declare namespace sort {
1221
+ var defaultOptions: {
1222
+ ignoreCase: true;
1223
+ newInstance: false;
1224
+ reverse: false;
1225
+ undefinedFirst: false;
1226
+ };
1227
+ }
1228
+
1229
+ /**
1230
+ * Creates a new Map by combining two or more Maps
1231
+ *
1232
+ * @param inputs A rest parameter of Maps and/or Map-entry (key-value pair tuples) Array.
1233
+ *
1234
+ * @returns new combined Map
1235
+ *
1236
+ * @example Join two Maps
1237
+ * ```typescript
1238
+ * import { mapJoin } from '@superutils/core'
1239
+ *
1240
+ * const maps = [
1241
+ * new Map([['a', 1]]),
1242
+ * new Map([['b', 2]]),
1243
+ * ]
1244
+ * const joined = mapJoin(...maps)
1245
+ * // Result: Map(2) {'a' => 1, 'b' => 2}
1246
+ * ```
1247
+ *
1248
+ * @example Join entries and Maps into a single Map
1249
+ * ```typescript
1250
+ * import { mapJoin } from '@superutils/core'
1251
+ *
1252
+ * const joined = mapJoin(
1253
+ * new Map([['a', 1]]),
1254
+ * [['b', 2]],
1255
+ * new Map([['c', 3]]),
1256
+ * )
1257
+ * // Result: Map(2) {'a' => 1, 'b' => 2, 'c' => 3}
1258
+ * ```
1259
+ */
1260
+ declare const mapJoin: <K, V>(...inputs: (Map<K, V> | [K, V][])[]) => Map<K, V>;
1261
+
1262
+ /**
1263
+ * Generates random number within a range
1264
+ *
1265
+ * @param min lowest number
1266
+ * @param max highest number
1267
+ */
1268
+ declare const randomInt: (min?: number, max?: number) => number;
1269
+
1270
+ /**
1271
+ * Clears clutter from strings
1272
+ *
1273
+ * - removes trailing & leading whitespaces
1274
+ * - removes empty/whitespace-only lines
1275
+ * - converts multiline strings to single line
1276
+ *
1277
+ * @param text string to clear clutter from
1278
+ * @param lineSeparator (optional) string to use as line separator. Default: single space `' '`
1279
+ *
1280
+ * @returns cleaned string
1281
+ */
1282
+ declare const clearClutter: (text: string, lineSeparator?: string) => string;
1283
+
1284
+ /**
1285
+ * @summary Copies text to browser clipboard.
1286
+ *
1287
+ * CAUTION:
1288
+ * Based on browser security policy it may be required to invoke `copyToClipboard` from an user-generated event handler.
1289
+ *
1290
+ * This function first attempts to use the modern, asynchronous Clipboard API (`window.navigator.clipboard.writeText`).
1291
+ * If that fails or is unavailable, it falls back to the legacy `document.execCommand('copy')` method.
1292
+ *
1293
+ *
1294
+ * @param {String} str
1295
+ *
1296
+ * @returns number
1297
+ * `0`: copy failed (both methods attempted)
1298
+ * `1`: modern API success
1299
+ * `2`: fallback success
1300
+ */
1301
+ declare const copyToClipboard: (str: string) => Promise<0 | 1 | 2>;
1302
+
1303
+ /**
1304
+ * Read parameters of a given URL
1305
+ *
1306
+ * @param name (optional) name of a specific parameter to get value of.
1307
+ * If not provided, will return an object containing all the URL parameters with respective values.
1308
+ * @param url (optional) default: `window.location.href`
1309
+ * @param asArray (optional) parameter names that should be returned as Array.
1310
+ * By default if a parameter contains multiple values it will be returned as unique Array.
1311
+ *
1312
+ * @returns {String|Object}
1313
+ */
1314
+ declare const getUrlParam: <TName extends string | undefined, TAsArray extends undefined | string[] | (TName extends undefined ? never : true), TResult = TName extends undefined ? Record<string, string> : string | string[]>(name?: TName, url?: string | URL, asArray?: TAsArray) => TResult;
1315
+
1316
+ declare const EMAIL_REGEX: RegExp;
1317
+ declare const HEX_REGEX: RegExp;
1318
+ declare const HASH_REGEX: RegExp;
1319
+
1320
+ export { type ArrayComparator, type AsyncFn, type CreateTuple, type CurriedArgs, type Curry, type DeferredConfig, type DropFirst, type DropFirstN, type DropLast, EMAIL_REGEX, type EntryComparator, type FindOptions, HASH_REGEX, HEX_REGEX, type IfPromiseAddValue, type IsFiniteTuple, type IsOptional, type IterableList, type KeepFirst, type KeepFirstN, type KeepOptionals, type KeepRequired, type MakeOptional, type MinLength, type OptionalIf, type ReadOnlyAllowAddFn, ReadOnlyArrayHelper, type ReadOnlyConfig, type SearchOptions, type Slice, type SliceMapCallback, type SliceMapOptions, type SortOptions, type ThrottleConfig, type TimeoutId, type TupleMaxLength, type TupleWithAlt, type ValueOrFunc, type ValueOrPromise, arrReadOnly, arrReverse, arrToMap, arrUnique, asAny, clearClutter, copyToClipboard, curry, debounce, deferred, fallbackIfFails, filter, find, forceCast, getEntries, getKeys, getSize, getUrlParam, getValues, is, isArr, isArr2D, isArrLike, isArrLikeSafe, isArrObj, isArrUnique, isAsyncFn, isBool, isDate, isDateValid, isDefined, isEmpty, isEmptySafe, isEnvBrowser, isEnvNode, isEnvTouchable, isError, isFn, isInteger, isMap, isMapObj, isNumber, isObj, isPositiveInteger, isPositiveNumber, isPromise, isRegExp, isSet, isStr, isSymbol, isUint8Arr, isUrl, isUrlValid, mapJoin, matchItemOrProp, noop, noopAsync, objClean, objCopy, objCreate, objKeys, objReadOnly, objSetProp, objSetPropUndefined, objSort, objWithoutKeys, randomInt, reverse, search, sliceMap, sort, throttled, toDatetimeLocal };