UNPKG

core-ts-utils

Version:
426 lines (391 loc) 14.2 kB
/** * Creates a debounced version of the given function that delays its execution * until after the specified delay has elapsed since the last time it was invoked. * * @template T - The type of the original function. * @param {T} func - The function to debounce. * @param {number} [delay=300] - The number of milliseconds to delay. * @returns {T} - A debounced version of the original function. * * @example * const log = (msg: string) => console.log(msg); * const debouncedLog = debounce(log, 500); * window.addEventListener('resize', () => debouncedLog('resized')); */ declare function debounce<T extends (...args: any[]) => void>(func: T, delay?: number): T; /** * Creates a throttled version of the given function that only allows it to be executed * once within a specified time limit. * * @template T - The type of the function to throttle. * @param {T} func - The function to throttle. * @param {number} limit - The minimum time (in milliseconds) between function calls. * @returns {T} - A new function that will only execute the original function at most once per `limit` period. * * @example * const log = (message: string) => console.log(message); * const throttledLog = throttle(log, 1000); * throttledLog("Hello"); // Executes immediately * throttledLog("World"); // Ignored * setTimeout(() => throttledLog("Delayed"), 1200); // Executes after 1200ms */ declare function throttle<T extends (...args: any[]) => void>(func: T, limit: number): T; /** * Transforms a function into its curried version. * * A curried function allows partial application of arguments until all expected arguments are received. * * @template T - The type of the original function. * @param {T} fn - The original function to curry. * @returns {Function} - A curried version of the original function. * * @example * const add = (a: number, b: number, c: number) => a + b + c; * const curriedAdd = curry(add); * curriedAdd(1)(2)(3); // 6 * curriedAdd(1, 2)(3); // 6 * curriedAdd(1)(2, 3); // 6 */ declare function curry<T extends (...args: any[]) => void>(fn: T): any; /** * Memoizes a function by caching its computed results based on arguments. * * Works for functions with serializable arguments (i.e., JSON.stringify-compatible). * * @template T - The type of the function to memoize. * @param {T} fn - The function to memoize. * @returns {T} - A new memoized version of the function. * * @example * const slowFn = (a: number, b: number) => a + b; * const memoizedFn = memoize(slowFn); * memoizedFn(1, 2); // Computes and caches * memoizedFn(1, 2); // Returns cached result */ declare function memoize<T extends (...args: any[]) => any>(fn: T): T; /** * Creates a function that invokes the provided function only once. * Subsequent calls return the result of the first invocation. * * @template T - The type of the original function. * @param {T} fn - The function to be executed once. * @returns {(...args: Parameters<T>) => ReturnType<T>} - A new function that only executes once. * * @example * const init = () => console.log("Initialized"); * const runOnce = once(init); * runOnce(); // "Initialized" * runOnce(); // No output */ declare function once<T extends (...args: any[]) => void>(fn: T): (this: ThisParameterType<T>, ...args: Parameters<T>) => any; /** * Creates a deep clone of a serializable object using JSON serialization. * * Note: This method does not support functions, `undefined`, `Date`, `Map`, `Set`, RegExp, or circular references. * * @template T - The type of the object to clone. * @param {T} obj - The object to deep clone. * @returns {T} - A deep copy of the input object. * * @example * const original = { a: 1, b: { c: 2 } }; * const clone = deepClone(original); * clone.b.c = 3; * console.log(original.b.c); // 2 */ declare function deepClone<T>(obj: T): T; /** * Generates a pseudo-random alphanumeric string ID of the specified length. * Combines current timestamp and random characters, then shuffles them. * * @param {number} [length=10] - The desired length of the generated ID. * @returns {string} - A random string ID of the specified length. * * @example * randomId(); // e.g., "k1x9v2q38z" * randomId(5); // e.g., "a8z3f" */ declare function randomId(length?: number): string; /** * Pauses execution for a specified number of milliseconds. * * @param {number} [ms=1000] - The number of milliseconds to sleep. Defaults to 1000ms. * @returns {Promise<void>} - A promise that resolves after the specified delay. * * @example * await sleep(2000); // Pauses execution for 2 seconds * await sleep(); // Pauses execution for 1 second (default) */ declare function sleep(ms?: number): Promise<void>; /** * Recursively flattens a nested array of any depth. * * @template T - The type of the elements in the array. * @param {any[]} arr - The nested array to flatten. * @returns {T[]} - A new flattened array containing all the elements. * * @example * flatten<number>([1, [2, [3, 4]], 5]); // [1, 2, 3, 4, 5] */ declare function flatten<T>(arr: any[]): T[]; /** * Capitalizes the first letter of a given string. * * @param {string} str - The input string to be capitalized. * @returns {string} The capitalized string. */ declare function capitalize(str: string): string; /** * Checks if a given value is empty. * * A value is considered empty if it is: * - an empty string * - null or undefined * - an empty object (`{}`) * - an empty array (`[]`) * * @param {any} obj - The value to check. * @returns {boolean} - `true` if the value is empty, otherwise `false`. * * @example * isEmpty(""); // true * isEmpty([]); // true * isEmpty({}); // true * isEmpty(null); // true * isEmpty(undefined); // true * isEmpty("text"); // false * isEmpty([1, 2]); // false */ declare function isEmpty(obj: any): boolean; /** * Splits an array into chunks of specified size * @param array - The array to chunk * @param size - The size of each chunk * @returns Array of chunks */ declare function chunk<T>(array: T[], size?: number): T[][]; /** * Groups the elements of an array based on the result of a callback function * @param array - The array to group * @param iteratee - The function or property name to group by * @returns An object with keys representing groups and values as arrays of matching elements */ declare function groupBy<T>(array: T[], iteratee: ((item: T) => string | number) | string): Record<string, T[]>; /** * Creates a new object excluding the specified properties * @param object - The source object * @param paths - The property paths to omit * @returns New object without the omitted properties */ declare function omit<T extends Record<string, any>, K extends keyof T>(object: T, paths: K[] | K): Omit<T, K>; /** * Creates a new object with only the specified properties * @param object - The source object * @param paths - The property paths to pick * @returns New object with only the picked properties */ declare function pick<T extends Record<string, any>, K extends keyof T>(object: T, paths: K[] | K): Pick<T, K>; /** * Deep merges multiple objects into a new object * @param objects - Objects to merge * @returns A new object with properties from all input objects */ declare function merge<T extends Record<string, any>>(...objects: (T | undefined | null)[]): T; /** * Returns unique array elements based on a key or function result * @param array - The array to process * @param iteratee - The function or property name to determine uniqueness * @returns Array with unique elements */ declare function uniqueBy<T>(array: T[], iteratee: ((item: T) => any) | keyof T): T[]; /** * Converts a string to camelCase * @param str - The string to convert * @returns Camel cased string */ declare function camelCase(str: string): string; /** * Converts a string to kebab-case * @param str - The string to convert * @returns Kebab cased string */ declare function kebabCase(str: string): string; /** * Converts a string to snake_case * @param str - The string to convert * @returns Snake cased string */ declare function snakeCase(str: string): string; /** * Truncates a string if it's longer than the given maximum length * @param str - The string to truncate * @param maxLength - Maximum length of the string * @param suffix - String to add at the end if truncated (default: '...') * @returns Truncated string */ declare function truncate(str: string, maxLength: number, suffix?: string): string; /** * Simple string template function with placeholders * @param template - String template with {placeholder} syntax * @param data - Object with values to replace placeholders * @returns Formatted string */ declare function template(template: string, data: Record<string, any>): string; /** * Composes functions from right to left * @param fns - Functions to compose * @returns Composed function */ declare function compose<T>(...fns: Array<(arg: T) => T>): (arg: T) => T; /** * Pipes value through a series of functions from left to right * @param fns - Functions to pipe through * @returns Piped function */ declare function pipe<T>(...fns: Array<(arg: T) => T>): (arg: T) => T; /** * Partially applies a function, binding some arguments * @param fn - Function to partially apply * @param args - Arguments to bind * @returns Partially applied function */ declare function partial<T, R>(fn: (...args: any[]) => R, ...args: any[]): (...remainingArgs: any[]) => R; /** * Checks if a string is a valid email address * @param value - String to check * @returns Boolean indicating if the string is a valid email */ declare function isEmail(value: string): boolean; /** * Checks if a string is a valid URL * @param value - String to check * @returns Boolean indicating if the string is a valid URL */ declare function isURL(value: string): boolean; /** * Checks if a value is numeric * @param value - Value to check * @returns Boolean indicating if the value is numeric */ declare function isNumeric(value: any): boolean; /** * Simple cookie management utility */ declare const cookies: { /** * Get cookie value by name * @param name - Cookie name * @returns Cookie value or null if not found */ get(name: string): string | null; /** * Set a cookie * @param name - Cookie name * @param value - Cookie value * @param options - Cookie options */ set(name: string, value: string, options?: { expires?: number | Date | string; path?: string; domain?: string; secure?: boolean; sameSite?: "strict" | "lax" | "none"; [key: string]: any; }): void; /** * Delete a cookie * @param name - Cookie name * @param options - Cookie options */ delete(name: string, options?: { path?: string; domain?: string; }): void; }; /** * Enhanced localStorage wrapper with expiration and object support */ declare const storage: { /** * Set a value in localStorage with optional expiration * @param key - Storage key * @param value - Value to store * @param expiresInMs - Milliseconds until expiration (optional) */ set(key: string, value: any, expiresInMs?: number): void; /** * Get a value from localStorage * @param key - Storage key * @param defaultValue - Default value if not found or expired * @returns Stored value or defaultValue */ get<T>(key: string, defaultValue?: T | null): T | null; /** * Remove a value from localStorage * @param key - Storage key */ remove(key: string): void; /** * Clear all values in localStorage */ clear(): void; }; /** * Parse and manipulate URL query parameters */ declare const queryParams: { /** * Get all query parameters as an object * @param url - URL to parse (defaults to current URL) * @returns Object with all query parameters */ getAll(url?: string): Record<string, string>; /** * Get a specific query parameter * @param name - Parameter name * @param url - URL to parse (defaults to current URL) * @returns Parameter value or null if not found */ get(name: string, url?: string): string | null; /** * Set query parameters and return the new URL * @param params - Parameters to set * @param url - Base URL (defaults to current URL) * @returns New URL with updated parameters */ set(params: Record<string, string>, url?: string): string; /** * Remove query parameters and return the new URL * @param paramNames - Parameter names to remove * @param url - Base URL (defaults to current URL) * @returns New URL with parameters removed */ remove(paramNames: string | string[], url?: string): string; }; /** * Retry a function with exponential backoff * @param fn - Async function to retry * @param options - Retry options * @returns Promise that resolves with the function result */ declare function retry<T>(fn: () => Promise<T>, options?: { maxAttempts?: number; initialDelay?: number; maxDelay?: number; factor?: number; onRetry?: (error: Error, attempt: number) => void; }): Promise<T>; /** * Convert callback-style function to Promise-based function * @param fn - Function with callback as last argument * @returns Promise-based function */ declare function promisify<T>(fn: (...args: any[]) => void): (...args: any[]) => Promise<T>; /** * Run async functions in parallel with concurrency limit * @param tasks - Array of async functions to run * @param concurrency - Maximum number of concurrent tasks * @returns Promise that resolves to array of results */ declare function parallel<T>(tasks: Array<() => Promise<T>>, concurrency?: number): Promise<T[]>; export { camelCase, capitalize, chunk, compose, cookies, curry, debounce, deepClone, flatten, groupBy, isEmail, isEmpty, isNumeric, isURL, kebabCase, memoize, merge, omit, once, parallel, partial, pick, pipe, promisify, queryParams, randomId, retry, sleep, snakeCase, storage, template, throttle, truncate, uniqueBy };