@ts-utilities/core 1.0.2 → 1.0.4

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.
@@ -1,679 +0,0 @@
1
- //#region src/functions/deepmerge.d.ts
2
- type TAllKeys<T> = T extends any ? keyof T : never;
3
- type TIndexValue<T, K$1 extends PropertyKey, D = never> = T extends any ? K$1 extends keyof T ? T[K$1] : D : never;
4
- type TPartialKeys<T, K$1 extends keyof T> = Omit<T, K$1> & Partial<Pick<T, K$1>> extends infer O ? { [P in keyof O]: O[P] } : never;
5
- type TFunction = (...a: any[]) => any;
6
- type TPrimitives = string | number | boolean | bigint | symbol | Date | TFunction;
7
- type DeepMergeOptions = {
8
- arrayMerge?: 'replace' | 'concat' | 'merge' | ((target: any[], source: any[]) => any[]);
9
- clone?: boolean;
10
- customMerge?: (key: string | symbol, targetValue: any, sourceValue: any) => any;
11
- functionMerge?: 'replace' | 'compose';
12
- maxDepth?: number;
13
- };
14
- type TMerged<T> = [T] extends [Array<any>] ? { [K in keyof T]: TMerged<T[K]> } : [T] extends [TPrimitives] ? T : [T] extends [object] ? TPartialKeys<{ [K in TAllKeys<T>]: TMerged<TIndexValue<T, K>> }, never> : T;
15
- /**
16
- * Deeply merges multiple objects, with later sources taking precedence.
17
- * Handles nested objects, arrays, and special object types with circular reference detection.
18
- *
19
- * Features:
20
- * - Deep merging of nested objects
21
- * - Configurable array merging strategies
22
- * - Circular reference detection and handling
23
- * - Support for symbols and special objects (Date, RegExp, etc.)
24
- * - Type-safe with improved generics
25
- * - Optional cloning to avoid mutation
26
- * - Custom merge functions for specific keys
27
- *
28
- * @template T - The target object type
29
- * @param target - The target object to merge into
30
- * @param sources - Source objects to merge from (can have additional properties)
31
- * @param options - Configuration options
32
- * @param options.clone - Whether to clone the target (default: true)
33
- * @param options.customMerge - Custom merge function for specific keys
34
- * @param options.arrayMerge - How to merge arrays: 'replace' (default), 'concat', or 'merge'
35
- * @param options.functionMerge - How to merge functions: 'replace' (default) or 'compose'
36
- * @param options.maxDepth - Maximum recursion depth (default: 100)
37
- * @returns The merged object with proper typing
38
- *
39
- * @example
40
- * // Basic shallow merge
41
- * deepmerge({ a: 1 }, { b: 2 }) // { a: 1, b: 2 }
42
- *
43
- * @example
44
- * // Deep merge of nested objects
45
- * deepmerge({ user: { name: 'John' } }, { user: { age: 30 } })
46
- * // { user: { name: 'John', age: 30 } }
47
- *
48
- * @example
49
- * // Array concatenation
50
- * deepmerge({ tags: ['react'] }, { tags: ['typescript'] }, { arrayMerge: 'concat' })
51
- * // { tags: ['react', 'typescript'] }
52
- *
53
- * @example
54
- * // Array replacement (default)
55
- * deepmerge({ items: [1, 2] }, { items: [3, 4] })
56
- * // { items: [3, 4] }
57
- *
58
- * @example
59
- * // Custom array merging
60
- * deepmerge(
61
- * { scores: [85, 90] },
62
- * { scores: [95] },
63
- * { arrayMerge: (target, source) => [...target, ...source] }
64
- * )
65
- * // { scores: [85, 90, 95] }
66
- *
67
- * @example
68
- * // Configuration merging
69
- * const defaultConfig = { theme: 'light', features: { darkMode: false } };
70
- * const userConfig = { theme: 'dark', features: { darkMode: true, animations: true } };
71
- * deepmerge(defaultConfig, userConfig);
72
- * // { theme: 'dark', features: { darkMode: true, animations: true } }
73
- *
74
- * @example
75
- * // State updates in reducers
76
- * const initialState = { user: { profile: { name: '' } }, settings: {} };
77
- * const action = { user: { profile: { name: 'Alice' } }, settings: { theme: 'dark' } };
78
- * const newState = deepmerge(initialState, action);
79
- *
80
- * @example
81
- * // Merging API responses
82
- * const cachedData = { posts: [{ id: 1, title: 'Old' }] };
83
- * const freshData = { posts: [{ id: 1, title: 'Updated', author: 'Bob' }] };
84
- * deepmerge(cachedData, freshData);
85
- * // { posts: [{ id: 1, title: 'Updated', author: 'Bob' }] }
86
- *
87
- * @example
88
- * // Function composition
89
- * const log1 = () => console.log('first');
90
- * const log2 = () => console.log('second');
91
- * const composed = deepmerge(log1, log2, { functionMerge: 'compose' });
92
- * composed(); // logs 'first' then 'second'
93
- */
94
- declare function deepmerge<T extends Record<string, any>, S extends Record<string, any>[]>(target: T, ...sources: S): TMerged<T | S[number]>;
95
- declare function deepmerge<T extends Record<string, any>, S extends Record<string, any>[]>(target: T, sources: S, options?: DeepMergeOptions): TMerged<T | S[number]>;
96
- //#endregion
97
- //#region src/functions/hydrate.d.ts
98
- type Hydrate<T> = T extends null ? undefined : T extends (infer U)[] ? Hydrate<U>[] : T extends object ? { [K in keyof T]: Hydrate<T[K]> } : T;
99
- /**
100
- * Converts all `null` values to `undefined` in the data structure recursively.
101
- *
102
- * @param data - Any input data (object, array, primitive)
103
- * @returns Same type as input, but with all nulls replaced by undefined
104
- *
105
- * @example
106
- * ```ts
107
- * // Basic object hydration
108
- * hydrate({ name: null, age: 25 }) // { name: undefined, age: 25 }
109
- *
110
- * // Nested object hydration
111
- * hydrate({
112
- * user: { email: null, profile: { avatar: null } },
113
- * settings: { theme: 'dark' }
114
- * })
115
- * // { user: { email: undefined, profile: { avatar: undefined } }, settings: { theme: 'dark' } }
116
- *
117
- * // Array hydration
118
- * hydrate([null, 'hello', null, 42]) // [undefined, 'hello', undefined, 42]
119
- *
120
- * // Mixed data structures
121
- * hydrate({
122
- * posts: [null, { title: 'Hello', content: null }],
123
- * metadata: { published: null, tags: ['react', null] }
124
- * })
125
- * ```
126
- *
127
- * @example
128
- * ```ts
129
- * // API response normalization
130
- * const apiResponse = await fetch('/api/user');
131
- * const rawData = await apiResponse.json(); // May contain null values
132
- * const normalizedData = hydrate(rawData); // Convert nulls to undefined
133
- *
134
- * // Database result processing
135
- * const dbResult = query('SELECT * FROM users'); // Some fields may be NULL
136
- * const cleanData = hydrate(dbResult); // Normalize for consistent handling
137
- *
138
- * // Form data sanitization
139
- * const formData = getFormValues(); // May have null values from empty fields
140
- * const sanitizedData = hydrate(formData); // Prepare for validation/state
141
- * ```
142
- */
143
- declare function hydrate<T>(data: T): Hydrate<T>;
144
- //#endregion
145
- //#region src/functions/object.d.ts
146
- /**
147
- * Type representing a path split into segments
148
- * @template S - The original path string type
149
- */
150
- type SplitPath<S extends string> = S extends `${infer First}.${infer Rest}` ? [First, ...SplitPath<Rest>] : [S];
151
- /**
152
- * Recursive type to resolve nested object types based on path
153
- * @template T - Current object type
154
- * @template K - Array of path segments
155
- */
156
- type GetValue<T, K$1 extends Array<string | number>> = K$1 extends [infer First, ...infer Rest] ? First extends keyof T ? GetValue<T[First], Rest extends Array<string | number> ? Rest : []> : First extends `${number}` ? T extends any[] ? GetValue<T[number], Rest extends Array<string | number> ? Rest : []> : undefined : undefined : T;
157
- /**
158
- * Get a nested value from an object using array path segments
159
- * @template T - Object type
160
- * @template K - Path segments array type
161
- * @template D - Default value type
162
- * @param obj - Source object
163
- * @param path - Array of path segments
164
- * @param defaultValue - Fallback value if path not found
165
- * @returns Value at path or default value
166
- *
167
- * @example
168
- * getObjectValue({a: [{b: 1}]}, ['a', 0, 'b']) // 1
169
- */
170
- declare function getObjectValue<T, K$1 extends Array<string | number>, D>(obj: T, path: K$1, defaultValue: D): Exclude<GetValue<T, K$1>, undefined> | D;
171
- /**
172
- * Get a nested value from an object using array path segments
173
- * @template T - Object type
174
- * @template K - Path segments array type
175
- * @param obj - Source object
176
- * @param path - Array of path segments
177
- * @returns Value at path or undefined
178
- *
179
- * @example
180
- * getObjectValue({a: [{b: 1}]}, ['a', 0, 'b']) // 1
181
- */
182
- declare function getObjectValue<T, K$1 extends Array<string | number>>(obj: T, path: K$1): GetValue<T, K$1> | undefined;
183
- /**
184
- * Get a nested value from an object using dot notation path
185
- * @template T - Object type
186
- * @template S - Path string literal type
187
- * @template D - Default value type
188
- * @param obj - Source object
189
- * @param path - Dot-separated path string
190
- * @param defaultValue - Fallback value if path not found
191
- * @returns Value at path or default value
192
- *
193
- * @example
194
- * getObjectValue({a: [{b: 1}]}, 'a.0.b', 2) // 1
195
- */
196
- declare function getObjectValue<T, S extends string, D>(obj: T, path: S, defaultValue: D): Exclude<GetValue<T, SplitPath<S>>, undefined> | D;
197
- /**
198
- * Get a nested value from an object using dot notation path
199
- * @template T - Object type
200
- * @template S - Path string literal type
201
- * @param obj - Source object
202
- * @param path - Dot-separated path string
203
- * @returns Value at path or undefined
204
- *
205
- * @example
206
- * getObjectValue({a: [{b: 1}]}, 'a.0.b') // 1
207
- */
208
- declare function getObjectValue<T, S extends string>(obj: T, path: S): GetValue<T, SplitPath<S>> | undefined;
209
- /**
210
- * Extend an object or function with additional properties while
211
- * preserving the original type information.
212
- *
213
- * Works with both plain objects and callable functions since
214
- * functions in JavaScript are objects too. Also handles nullable types.
215
- *
216
- * @template T The base object or function type (can be null/undefined)
217
- * @template P The additional properties type
218
- *
219
- * @param base - The object or function to extend (can be null/undefined)
220
- * @param props - An object containing properties to attach
221
- *
222
- * @returns The same object/function, augmented with the given properties, or the original value if null/undefined
223
- *
224
- * @example
225
- * ```ts
226
- * // Extend a plain object
227
- * const config = extendProps({ apiUrl: '/api' }, { timeout: 5000 });
228
- * // config has both apiUrl and timeout properties
229
- *
230
- * // Extend a function with metadata
231
- * const fetchData = (url: string) => fetch(url).then(r => r.json());
232
- * const enhancedFetch = extendProps(fetchData, {
233
- * description: 'Data fetching utility',
234
- * version: '1.0'
235
- * });
236
- * // enhancedFetch is callable and has description/version properties
237
- *
238
- * // Create plugin system
239
- * const basePlugin = { name: 'base', enabled: true };
240
- * const authPlugin = extendProps(basePlugin, {
241
- * authenticate: (token: string) => validateToken(token)
242
- * });
243
- *
244
- * // Build configuration objects
245
- * const defaultSettings = { theme: 'light', lang: 'en' };
246
- * const userSettings = extendProps(defaultSettings, {
247
- * theme: 'dark',
248
- * notifications: true
249
- * });
250
- *
251
- * // Handle nullable types (e.g., Supabase Session | null)
252
- * const session: Session | null = getSession();
253
- * const extendedSession = extendProps(session, { customProp: 'value' });
254
- * // extendedSession is (Session & { customProp: string }) | null
255
- * ```
256
- */
257
- declare function extendProps<T, P$1 extends object>(base: T, props: P$1): T extends null | undefined ? T : T & P$1;
258
- //#endregion
259
- //#region src/functions/poll.d.ts
260
- /**
261
- * Repeatedly polls an async `cond` function UNTIL it returns a TRUTHY value,
262
- * or until the operation times out or is aborted.
263
- *
264
- * Designed for waiting on async jobs, external state, or delayed availability.
265
- *
266
- * @template T The type of the successful result.
267
- *
268
- * @param cond
269
- * A function returning a Promise that resolves to:
270
- * - a truthy value `T` → stop polling and return it
271
- * - falsy/null/undefined → continue polling
272
- *
273
- * @param options
274
- * Configuration options:
275
- * - `interval` (number) — Time between polls in ms (default: 5000 ms)
276
- * - `timeout` (number) — Max total duration before failing (default: 5 min)
277
- * - `jitter` (boolean) — Add small random offset (±10%) to intervals to avoid sync bursts (default: true)
278
- * - `signal` (AbortSignal) — Optional abort signal to cancel polling
279
- *
280
- * @returns
281
- * Resolves with the truthy value `T` when successful.
282
- * Throws `AbortError` if aborted
283
- *
284
- * @example
285
- * ```ts
286
- * // Poll for job completion
287
- * const job = await poll(async () => {
288
- * const status = await getJobStatus();
289
- * return status === 'done' ? status : null;
290
- * }, { interval: 3000, timeout: 60000 });
291
- * ```
292
- *
293
- * @example
294
- * ```ts
295
- * // Wait for API endpoint to be ready
296
- * const apiReady = await poll(async () => {
297
- * try {
298
- * await fetch('/api/health');
299
- * return true;
300
- * } catch {
301
- * return null;
302
- * }
303
- * }, { interval: 1000, timeout: 30000 });
304
- * ```
305
- *
306
- * @example
307
- * ```ts
308
- * // Poll with abort signal for cancellation
309
- * const controller = new AbortController();
310
- * setTimeout(() => controller.abort(), 10000); // Cancel after 10s
311
- *
312
- * try {
313
- * const result = await poll(
314
- * () => checkExternalService(),
315
- * { interval: 2000, signal: controller.signal }
316
- * );
317
- * } catch (err) {
318
- * if (err.name === 'AbortError') {
319
- * console.log('Polling was cancelled');
320
- * }
321
- * }
322
- * ```
323
- *
324
- * @example
325
- * ```ts
326
- * // Poll for user action completion
327
- * const userConfirmed = await poll(async () => {
328
- * const confirmations = await getPendingConfirmations();
329
- * return confirmations.length > 0 ? confirmations[0] : null;
330
- * }, { interval: 5000, timeout: 300000 }); // 5 min timeout
331
- * ```
332
- */
333
- declare function poll<T>(cond: () => Promise<T | null | false | undefined>, {
334
- interval,
335
- timeout,
336
- jitter,
337
- signal
338
- }?: Partial<{
339
- interval: number;
340
- timeout: number;
341
- signal: AbortSignal;
342
- jitter: boolean;
343
- }>): Promise<T>;
344
- //#endregion
345
- //#region src/functions/schedule.d.ts
346
- /**
347
- * A task function that can be synchronous or asynchronous.
348
- */
349
- type Task = () => Promise<void> | void;
350
- /**
351
- * Options for configuring the schedule function.
352
- */
353
- interface ScheduleOpts {
354
- /** Number of retry attempts on failure. Defaults to 0. */
355
- retry?: number;
356
- /** Delay in milliseconds between retries. Defaults to 0. */
357
- delay?: number;
358
- /** Maximum time in milliseconds to wait for the task to complete. */
359
- timeout?: number;
360
- }
361
- /**
362
- * Runs a function asynchronously in the background without blocking the main thread.
363
- *
364
- * Executes the task immediately using setTimeout, with optional retry logic on failure.
365
- * Useful for non-critical operations like analytics, logging, or background processing.
366
- * Logs execution time and retry attempts to the console.
367
- *
368
- * @param task - The function to execute asynchronously
369
- * @param options - Configuration options for retries and timing
370
- *
371
- * @example
372
- * ```ts
373
- * // Simple background task
374
- * schedule(() => {
375
- * console.log('Background work done');
376
- * });
377
- *
378
- * // Task with retry on failure
379
- * schedule(
380
- * () => sendAnalytics(),
381
- * { retry: 3, delay: 1000 }
382
- * );
383
- * ```
384
- */
385
- declare function schedule(task: Task, options?: ScheduleOpts): void;
386
- //#endregion
387
- //#region src/functions/shield.d.ts
388
- /**
389
- * A helper to run sync or async operations safely without try/catch.
390
- *
391
- * Returns a tuple `[error, data]`:
392
- * - `error`: the thrown error (if any), otherwise `null`
393
- * - `data`: the resolved value (if successful), otherwise `null`
394
- *
395
- * @example
396
- * ```ts
397
- * // Synchronous error handling
398
- * const [err, value] = shield(() => {
399
- * if (Math.random() > 0.5) throw new Error('Random failure');
400
- * return 'success';
401
- * });
402
- * if (err) {
403
- * console.error('Operation failed:', err);
404
- * } else {
405
- * console.log('Result:', value);
406
- * }
407
- *
408
- * // Asynchronous error handling
409
- * const [asyncErr, result] = await shield(async () => {
410
- * const response = await fetch('/api/data');
411
- * if (!response.ok) throw new Error('API error');
412
- * return response.json();
413
- * });
414
- * if (asyncErr) {
415
- * console.error('API call failed:', asyncErr);
416
- * } else {
417
- * processData(result);
418
- * }
419
- *
420
- * // API calls with fallbacks
421
- * const [fetchErr, data] = await shield(fetchUserData(userId));
422
- * const userData = fetchErr ? getCachedUserData(userId) : data;
423
- *
424
- * // File operations
425
- * const [fileErr, content] = shield(() => readFileSync('config.json'));
426
- * if (fileErr) {
427
- * console.warn('Could not read config, using defaults');
428
- * return defaultConfig;
429
- * }
430
- * ```
431
- *
432
- * @example
433
- * ```ts
434
- * // In async functions
435
- * async function safeApiCall() {
436
- * const [err, result] = await shield(callExternalAPI());
437
- * if (err) {
438
- * await logError(err);
439
- * return null;
440
- * }
441
- * return result;
442
- * }
443
- *
444
- * // In event handlers
445
- * function handleSubmit(formData) {
446
- * const [validationErr, validatedData] = shield(() => validateForm(formData));
447
- * if (validationErr) {
448
- * showValidationError(validationErr);
449
- * return;
450
- * }
451
- * submitData(validatedData);
452
- * }
453
- * ```
454
- */
455
- declare function shield<T, E = Error>(operation: Promise<T>): Promise<[E | null, T | null]>;
456
- declare function shield<T, E = Error>(operation: () => T): [E | null, T | null];
457
- //#endregion
458
- //#region src/functions/utils-core.d.ts
459
- /**
460
- * Converts various case styles (camelCase, PascalCase, kebab-case, snake_case) into readable normal case.
461
- *
462
- * Transforms technical naming conventions into human-readable titles by:
463
- * - Adding spaces between words
464
- * - Capitalizing the first letter of each word
465
- * - Handling common separators (-, _, camelCase boundaries)
466
- *
467
- * @param inputString - The string to convert (supports camelCase, PascalCase, kebab-case, snake_case).
468
- * @returns The converted string in normal case (title case).
469
- *
470
- * @example
471
- * ```ts
472
- * convertToNormalCase('camelCase') // 'Camel Case'
473
- * convertToNormalCase('kebab-case') // 'Kebab Case'
474
- * convertToNormalCase('snake_case') // 'Snake Case'
475
- * convertToNormalCase('PascalCase') // 'Pascal Case'
476
- * ```
477
- */
478
- declare function convertToNormalCase(inputString: string): string;
479
- /**
480
- * Converts a string to a URL-friendly slug by trimming, converting to lowercase,
481
- * replacing diacritics, removing invalid characters, and replacing spaces with hyphens.
482
- * @param {string} [str] - The input string to convert.
483
- * @returns {string} The generated slug.
484
- * @example
485
- * convertToSlug("Hello World!"); // "hello-world"
486
- * convertToSlug("Déjà Vu"); // "deja-vu"
487
- */
488
- declare const convertToSlug: (str: string) => string;
489
- /**
490
- * Pauses execution for the specified time.
491
- *
492
- * `signal` allows cancelling the sleep via AbortSignal.
493
- *
494
- * @param time - Time in milliseconds to sleep (default is 1000ms)
495
- * @param signal - Optional AbortSignal to cancel the sleep early
496
- * @returns - A Promise that resolves after the specified time or when aborted
497
- */
498
- declare const sleep: (time?: number, signal?: AbortSignal) => Promise<void>;
499
- type DebouncedFunction<F extends (...args: any[]) => any> = {
500
- (...args: Parameters<F>): ReturnType<F> | undefined;
501
- readonly isPending: boolean;
502
- };
503
- /**
504
- * Creates a debounced function that delays invoking the provided function until
505
- * after the specified `wait` time has elapsed since the last invocation.
506
- *
507
- * If the `immediate` option is set to `true`, the function will be invoked immediately
508
- * on the leading edge of the wait interval. Subsequent calls during the wait interval
509
- * will reset the timer but not invoke the function until the interval elapses again.
510
- *
511
- * The returned function includes the `isPending` property to check if the debounce
512
- * timer is currently active.
513
- *
514
- * @typeParam F - The type of the function to debounce.
515
- *
516
- * @param function_ - The function to debounce.
517
- * @param wait - The number of milliseconds to delay (default is 100ms).
518
- * @param options - An optional object with the following properties:
519
- * - `immediate` (boolean): If `true`, invokes the function on the leading edge
520
- * of the wait interval instead of the trailing edge.
521
- *
522
- * @returns A debounced version of the provided function, enhanced with the `isPending` property.
523
- *
524
- * @throws {TypeError} If the first parameter is not a function.
525
- * @throws {RangeError} If the `wait` parameter is negative.
526
- *
527
- * @example
528
- * ```ts
529
- * // Basic debouncing
530
- * const log = debounce((message: string) => console.log(message), 200);
531
- * log('Hello'); // Logs "Hello" after 200ms if no other call is made.
532
- * console.log(log.isPending); // true if the timer is active.
533
- *
534
- * // Immediate execution
535
- * const save = debounce(() => saveToServer(), 500, { immediate: true });
536
- * save(); // Executes immediately, then waits 500ms for subsequent calls
537
- *
538
- * // Check pending state
539
- * const debouncedSearch = debounce(searchAPI, 300);
540
- * debouncedSearch('query');
541
- * if (debouncedSearch.isPending) {
542
- * showLoadingIndicator();
543
- * }
544
- * ```
545
- */
546
- declare function debounce<F extends (...args: any[]) => any>(function_: F, wait?: number, options?: {
547
- immediate: boolean;
548
- }): DebouncedFunction<F>;
549
- type ThrottledFunction<F extends (...args: any[]) => any> = {
550
- (...args: Parameters<F>): ReturnType<F> | undefined;
551
- readonly isPending: boolean;
552
- };
553
- /**
554
- * Creates a throttled function that invokes the provided function at most once
555
- * every `wait` milliseconds.
556
- *
557
- * If the `leading` option is set to `true`, the function will be invoked immediately
558
- * on the leading edge of the throttle interval. If the `trailing` option is set to `true`,
559
- * the function will also be invoked at the end of the throttle interval if additional
560
- * calls were made during the interval.
561
- *
562
- * The returned function includes the `isPending` property to check if the throttle
563
- * timer is currently active.
564
- *
565
- * @typeParam F - The type of the function to throttle.
566
- *
567
- * @param function_ - The function to throttle.
568
- * @param wait - The number of milliseconds to wait between invocations (default is 100ms).
569
- * @param options - An optional object with the following properties:
570
- * - `leading` (boolean): If `true`, invokes the function on the leading edge of the interval.
571
- * - `trailing` (boolean): If `true`, invokes the function on the trailing edge of the interval.
572
- *
573
- * @returns A throttled version of the provided function, enhanced with the `isPending` property.
574
- *
575
- * @throws {TypeError} If the first parameter is not a function.
576
- * @throws {RangeError} If the `wait` parameter is negative.
577
- *
578
- * @example
579
- * ```ts
580
- * // Basic throttling (leading edge by default)
581
- * const log = throttle((message: string) => console.log(message), 200);
582
- * log('Hello'); // Logs "Hello" immediately
583
- * log('World'); // Ignored for 200ms
584
- * console.log(log.isPending); // true if within throttle window
585
- *
586
- * // Trailing edge only
587
- * const trailingLog = throttle(() => console.log('trailing'), 200, {
588
- * leading: false,
589
- * trailing: true
590
- * });
591
- * trailingLog(); // No immediate execution
592
- * // After 200ms: logs "trailing"
593
- *
594
- * // Both edges
595
- * const bothLog = throttle(() => console.log('both'), 200, {
596
- * leading: true,
597
- * trailing: true
598
- * });
599
- * bothLog(); // Immediate execution
600
- * // After 200ms: executes again if called during window
601
- * ```
602
- */
603
- declare function throttle<F extends (...args: any[]) => any>(function_: F, wait?: number, options?: {
604
- leading?: boolean;
605
- trailing?: boolean;
606
- }): ThrottledFunction<F>;
607
- /**
608
- * Formats a string by replacing each '%s' placeholder with the corresponding argument.
609
- *
610
- * Mimics the basic behavior of C's printf for %s substitution. Supports both
611
- * variadic arguments and array-based argument passing. Extra placeholders
612
- * are left as-is, missing arguments result in empty strings.
613
- *
614
- * @param format - The format string containing '%s' placeholders.
615
- * @param args - The values to substitute, either as separate arguments or a single array.
616
- * @returns The formatted string with placeholders replaced by arguments.
617
- *
618
- * @example
619
- * ```ts
620
- * // Basic usage with separate arguments
621
- * printf("%s love %s", "I", "Bangladesh") // "I love Bangladesh"
622
- *
623
- * // Using array of arguments
624
- * printf("%s love %s", ["I", "Bangladesh"]) // "I love Bangladesh"
625
- *
626
- * // Extra placeholders remain unchanged
627
- * printf("%s %s %s", "Hello", "World") // "Hello World %s"
628
- *
629
- * // Missing arguments become empty strings
630
- * printf("%s and %s", "this") // "this and "
631
- *
632
- * // Multiple occurrences
633
- * printf("%s %s %s", "repeat", "repeat", "repeat") // "repeat repeat repeat"
634
- * ```
635
- */
636
- declare function printf(format: string, ...args: unknown[]): string;
637
- /**
638
- * Escapes a string for use in a regular expression.
639
- *
640
- * @param str - The string to escape
641
- * @returns - The escaped string safe for use in RegExp constructor
642
- *
643
- * @example
644
- * ```ts
645
- * const escapedString = escapeRegExp('Hello, world!');
646
- * // escapedString === 'Hello\\, world!'
647
- *
648
- * const regex = new RegExp(escapeRegExp(userInput));
649
- * ```
650
- */
651
- declare function escapeRegExp(str: string): string;
652
- /**
653
- * Normalizes a string by:
654
- * - Applying Unicode normalization (NFC)
655
- * - Optionally removing diacritic marks (accents)
656
- * - Optionally trimming leading/trailing non-alphanumeric characters
657
- * - Optionally converting to lowercase
658
- *
659
- * @param str - The string to normalize
660
- * @param options - Normalization options
661
- * @param options.lowercase - Whether to convert the result to lowercase (default: true)
662
- * @param options.removeAccents - Whether to remove diacritic marks like accents (default: true)
663
- * @param options.removeNonAlphanumeric - Whether to trim non-alphanumeric characters from the edges (default: true)
664
- * @returns The normalized string
665
- *
666
- * @example
667
- * ```ts
668
- * normalizeText('Café') // 'cafe'
669
- * normalizeText(' Hello! ') // 'hello'
670
- * normalizeText('José', { removeAccents: false }) // 'josé'
671
- * ```
672
- */
673
- declare function normalizeText(str?: string | null, options?: {
674
- lowercase?: boolean;
675
- removeAccents?: boolean;
676
- removeNonAlphanumeric?: boolean;
677
- }): string;
678
- //#endregion
679
- export { DeepMergeOptions as _, normalizeText as a, throttle as c, Task as d, schedule as f, hydrate as g, getObjectValue as h, escapeRegExp as i, shield as l, extendProps as m, convertToSlug as n, printf as o, poll as p, debounce as r, sleep as s, convertToNormalCase as t, ScheduleOpts as u, deepmerge as v };