UNPKG

funtool

Version:

A modern, efficient, and modular JavaScript utility library designed to enhance developer productivity.

1,538 lines (1,501 loc) 82.6 kB
declare const VERSION = "1.2.1"; /** * Retrieves the element at the specified index in the array. * Supports negative indices, which count from the end of the array. * * @template T - The type of elements in the array. * @param {T[]} arr - The input array. * @param {number} index - The index of the element to retrieve. Can be negative. * @returns {T | undefined} - The element at the specified index, or undefined if the index is out of bounds or the array is empty. * * @example * const arr = [1, 2, 3, 4, 5]; * at(arr, 2); // ✅ Returns 3 * at(arr, -1); // ✅ Returns 5 * at([], 0); // ✅ Returns undefined */ declare function at<T>(arr: T[], index: number): T | undefined; /** * Get the intersection of two arrays * @param arr1 - The first array * @param arr2 - The second array * @returns A new array containing elements present in both arrays * @example * intersect([1, 2, 3], [2, 3, 4]) // ✅ [2, 3] * intersect(['a', 'b'], ['b', 'c']) // ✅ ['b'] */ declare function intersect<T>(arr1: T[], arr2: T[]): T[]; /** * Remove specified values from an array * @param arr - The array to process * @param values - The values to remove * @returns A new array with specified values removed * @example * remove([1, 2, 3], [2]) // ✅ [1, 3] * remove(['a', 'b', 'c'], ['b', 'c']) // ✅ ['a'] */ declare function remove<T>(arr: T[], values: T[]): T[]; /** * Get the union of two arrays * @param arr1 - The first array * @param arr2 - The second array * @returns A new array containing elements from both arrays without duplicates * @example * union([1, 2], [2, 3]) // ✅ [1, 2, 3] * union(['a'], ['b', 'a']) // ✅ ['a', 'b'] */ declare function union<T>(arr1: T[], arr2: T[]): T[]; /** * Remove duplicate values from an array * @param arr - The array to process * @returns A new array with unique values * @example * unique([1, 2, 2, 3]) // ✅ [1, 2, 3] * unique(['a', 'b', 'a']) // ✅ ['a', 'b'] */ declare function unique<T>(arr: T[]): T[]; /** * A customizer function for `cloneWith`, used to transform values before cloning. * - If the customizer returns `undefined`, the default clone logic will be used. * - If a value is returned, it will be used instead of the default clone. */ type Customizer<T> = T extends any[] ? (val: T[number], index: number) => T[number] | undefined : T extends object ? (val: T[keyof T], key: keyof T) => T[keyof T] | undefined : never; /** * Creates a shallow clone of the given value. * * Supports a wide range of built-in JavaScript types including: * - Primitives (returned as-is) * - Arrays * - Date objects * - RegExp objects * - Map and Set * - TypedArrays (e.g. Uint8Array, Float32Array, etc.) * - DataView * - Plain objects (preserving prototype) * * This function **does not** perform deep cloning. * * @template T - The type of the value to clone * @param {T} value - The value to be cloned * @returns {T} - A shallow copy of the original value * * @example * // Clone an array * const arr = [1, 2, 3]; * const clonedArr = clone(arr); * console.log(clonedArr); // [1, 2, 3] * console.log(clonedArr === arr); // ❌ false * * @example * // Clone an object * const obj = { a: 1, b: { c: 2 } }; * const clonedObj = clone(obj); * console.log(clonedObj); // { a: 1, b: { c: 2 } } * console.log(clonedObj === obj); // ❌ false * console.log(clonedObj.b === obj.b); // ✅ true (shallow clone) * * @example * // Clone a Date * const date = new Date(); * const clonedDate = clone(date); * console.log(clonedDate); // Same date as original * console.log(clonedDate === date); // ❌ false * * @example * // Clone a Map * const map = new Map([['key', 'value']]); * const clonedMap = clone(map); * console.log(clonedMap.get('key')); // 'value' * console.log(clonedMap === map); // ❌ false */ declare function clone<T>(value: T): T; /** * Performs a shallow clone of `value`, invoking `customizer` to customize the cloned value. * If `customizer` returns a defined value, it is used instead of the default clone. * * @template T * @param value - The value to clone. * @param customizer - Optional customizer invoked with the value. * @returns {T} The cloned value. * * @example * const obj = { a: 1, b: 2 }; * const result = cloneWith(obj, (val) => typeof val === 'number' ? val + 1 : undefined); * // result => { a: 2, b: 3 } */ declare function cloneWith<T>(value: T, customizer: Customizer<T>): T; type Primitive = string | number | boolean | bigint | symbol | null | undefined; /** * Determines if a type is a Tuple (i.e., fixed-length array) * Tuples have known numeric literal keys and `length` is a constant number. */ type IsTuple<T> = T extends readonly any[] ? number extends T['length'] ? false : true : false; /** * Recursive deep copy type utility. * - Preserves tuples and arrays * - Removes `readonly` from properties * - Recursively copies object properties, including symbol keys */ type CloneDeep<T> = T extends Primitive | ((...args: any[]) => any) ? T : IsTuple<T> extends true ? { [K in keyof T]: CloneDeep<T[K]>; } : T extends ReadonlyArray<infer U> ? Array<CloneDeep<U>> : T extends Map<infer K, infer V> ? Map<K, CloneDeep<V>> : T extends Set<infer U> ? Set<CloneDeep<U>> : T extends Date ? Date : T extends RegExp ? RegExp : T extends object ? { -readonly [K in keyof T]: CloneDeep<T[K]>; } & { [K in keyof T as K extends symbol ? K : never]: CloneDeep<T[K]>; } : T; /** * @description Customizer function type for cloneDeepWith * If it returns `undefined`, cloneDeepWith falls back to default deep cloning logic */ type CloneDeepCustomizer = (value: any, key?: PropertyKey, object?: any) => any; /** * @description Deep copy an object. * Unsupported types like functions, symbols, WeakMap, WeakSet will trigger a warning and return original. * @param {any} obj - The object to deep copy * @param {WeakMap<object, any>} [seen=new WeakMap()] - WeakMap cache to track copied references * @returns {any} - Deep copied object * * @example * const original = { name: "Alice", details: { age: 25 } }; * const copy = cloneDeep(original); * console.log(copy.details.age); // ✅ 25 * console.log(copy !== original); // ✅ true * * @example * const arr = [1, { nested: true }, [3]]; * const copy = cloneDeep(arr); * console.log(copy[1].nested); // ✅ true * * @example * const map = new Map<string, number>([["a", 1], ["b", 2]]); * const copy = cloneDeep(map); * console.log(copy.get("b")); // ✅ 2 * * @example * const set = new Set([1, 2, 3]); * const copy = cloneDeep(set); * console.log(copy.has(2)); // ✅ true * * @example * const date = new Date("2020-01-01"); * const copy = cloneDeep(date); * console.log(copy.getFullYear()); // ✅ 2020 * * @example * const regex = /abc/gi; * const copy = cloneDeep(regex); * console.log(copy.source); // ✅ "abc" * console.log(copy.flags); // ✅ "gi" * * @example * const obj: any = {}; * obj.self = obj; * const copy = cloneDeep(obj); * console.log(copy.self === copy); // ✅ true */ declare function cloneDeep<T>(obj: T, seen?: WeakMap<object, any>): CloneDeep<T>; /** * @description Deep copy with customizer support. * @param {any} obj - The object to clone * @param {CloneDeepCustomizer} customizer - Custom clone handler, can override cloning behavior * @param {WeakMap<object, any>} [seen=new WeakMap()] - Circular reference cache * @returns {any} - Cloned object with possible customization * * @example * const original = { x: new Date(), y: 123 }; * const copy = cloneDeepWith(original, (val) => { * if (val instanceof Date) return 'DATE'; * }); * console.log(copy.x); // ✅ "DATE" */ declare function cloneDeepWith<T>(obj: T, customizer: CloneDeepCustomizer, seen?: WeakMap<object, any>): CloneDeep<T>; /** * Checks if a value exists in an array starting from a given index. * * @template T * @param {T[]} source - The array to search. * @param {T} target - The value to search for. * @param {number} [fromIndex=0] - The index to start searching from. * @returns {boolean} True if found, otherwise false. * @example * includes([1, 2, 3], 2); // ✅ true * includes([1, 2, 3], 2, 2); // ❌ false */ declare function includes<T>(source: T[], target: T, fromIndex?: number): boolean; /** * Checks if a substring exists in a string starting from a given index. * * @param {string} source - The string to search. * @param {string} target - The substring to search for. * @param {number} [fromIndex=0] - The index to start searching from. * @returns {boolean} True if found, otherwise false. * @example * includes('hello world', 'world'); // ✅ true * includes('hello world', 'world', 8); // ❌ false */ declare function includes(source: string, target: string, fromIndex?: number): boolean; /** * Checks if a value exists among the values of an object. * * @param {Record<string, any>} source - The object to search. * @param {*} target - The value to search for. * @returns {boolean} True if found, otherwise false. * @example * includes({ a: 1, b: 2 }, 2); // ✅ true */ declare function includes(source: Record<string, any>, target: any): boolean; /** * Checks if a key exists in a Map. * * @template K, V * @param {Map<K, V>} source - The Map to search. * @param {K} target - The key to search for. * @returns {boolean} True if found, otherwise false. * @example * includes(new Map([['a', 1], ['b', 2]]), 'b'); // ✅ true */ declare function includes<K, V>(source: Map<K, V>, target: K): boolean; /** * Checks if a value exists in a Set. * * @template T * @param {Set<T>} source - The Set to search. * @param {T} target - The value to search for. * @returns {boolean} True if found, otherwise false. * @example * includes(new Set([1, 2, 3]), 2); // ✅ true */ declare function includes<T>(source: Set<T>, target: T): boolean; /** * A lightweight ObjectId implementation supporting hex, UUID, base64, and prefix. * 轻量级 ObjectId 实现,支持 hex、UUID、base64、前缀等格式。 */ declare class ObjectId { private hex; /** * Create a new ObjectId instance. * 创建一个新的 ObjectId 实例。 * @param hex Optional hex string. If provided, it must be valid. * 可选 hex 字符串。如果提供,必须合法。 * @param randomFn Optional custom random function. * 可选的自定义随机函数。 */ constructor(hex?: string, randomFn?: () => number); /** * Validate a hex string. * 验证一个十六进制字符串是否合法。 * @param hex The hex string to validate. 要验证的十六进制字符串。 */ static isValid(hex: string): boolean; /** * Create an ObjectId from a valid hex string. * 从合法的 hex 字符串创建 ObjectId。 * @param hex A valid 24-character hex string. 合法的 24 位十六进制字符串。 */ static createFromHexString(hex: string): ObjectId; /** * Create an ObjectId string with prefix. * 创建带前缀的 ObjectId 字符串。 * @param prefix The prefix string. 前缀字符串。 */ static createWithPrefix(prefix: string): string; /** * Return the hex string. * 返回 hex 字符串。 */ toHex(): string; /** * Convert to Uint8Array buffer. * 转换为 Uint8Array 缓冲区。 */ toBuffer(): Uint8Array; /** * Check equality with another ObjectId. * 判断是否与另一个 ObjectId 相等。 */ equals(other: ObjectId): boolean; /** * Parse ObjectId from mixed-format string. * 从混合格式字符串解析 ObjectId。 * @param str Any string containing valid hex. 包含合法 hex 的任意字符串。 * @param strict - Whether to strictly validate full format. 是否严格校验格式。 * @example * ObjectId.parse("uuid-5f1d7f3b1c9d440000000000").toHex(); // => "5f1d7f3b1c9d440000000000" */ static parse(str: string, strict?: boolean): ObjectId; /** * Return the 24-char hex string. * 返回 24 位 hex 字符串。 */ toHexString(): string; /** * Convert to UUID-like format (padded to 128 bits). * 转换为 UUID 风格格式(补齐为 128 位)。 */ toUUIDString(): string; /** * Default string representation (hex). * 默认字符串表现形式(hex)。 */ toString(): string; /** * Convert to base64 string. * 转换为 base64 字符串。 */ toBase64(): string; /** * Convert to short ID (base64 with optional prefix). * 转换为短 ID(base64 编码,可选前缀)。 * @param prefix Optional prefix. 可选前缀。 */ short(prefix?: string): string; /** * Get timestamp in milliseconds. * 获取时间戳(单位:毫秒)。 */ getTimestamp(): number; /** * Compare with another ObjectId. * 与另一个 ObjectId 比较大小。 */ compare(other: ObjectId): number; /** * Clone the ObjectId. * 克隆当前 ObjectId。 */ clone(): ObjectId; /** * Ensure JSON.stringify outputs hex string. * 保证 JSON 序列化输出 hex 字符串。 */ toJSON(): string; } /** * Wrap a Promise or value to return a tuple of [error, data] instead of throwing. * 将 Promise 或值包装成返回 [错误, 数据] 的形式,避免 try/catch。 * * @template T - The type of the resolved data. * @param {Promise<T> | T} promiseOrValue - Promise or value to wrap. * 要包装的 Promise 或值。 * @returns {Promise<[unknown, undefined] | [null, T]>} A Promise resolving to a tuple. * 返回一个 Promise,解析为一个包含错误和数据的元组。 * * @example * ```ts * const [err, data] = await awaitTo(fetchData()); * if (err) { * // handle error * // 处理错误 * } * ``` */ declare function awaitTo<T>(promiseOrValue: Promise<T> | T): Promise<[unknown, undefined] | [null, T]>; /** * Base64. Convert base64 string to Blob object. * 将 base64 字符串转换为 Blob 对象(内部私有方法) * * @param {string} base64 - Base64 string, e.g., 'data:image/png;base64,...' * base64 字符串,必须包含 MIME 前缀 * @returns {{ blob: Blob; mime: string; ext: string }} Blob object, MIME type, and file extension * 返回 Blob 对象、MIME 类型、文件扩展名 * * @example * const { blob, mime, ext } = base64ToBlob(base64) */ declare function base64ToBlob(base64: string): { blob: Blob; mime: string; ext: string; }; /** * Base64. Convert base64 string to FormData with file field. * 将 base64 字符串转换为包含文件字段的 FormData 对象 * * @param {string} base64 - Base64 string with data URL format * 含有 data URL 前缀的 base64 字符串 * @param {Object} [options] - Optional configuration 配置项 * @param {string} [options.key="file"] - FormData field name (default: 'file') * FormData 中的字段名(默认 "file") * @param {string} [options.filename] - File name (with or without extension) * 文件名(可不带扩展名,将自动补全) * @returns {FormData} FormData instance with one file field * 包含一个文件字段的 FormData 对象 * * @example * const formData = base64ToFormData(base64, { * key: 'avatar', * filename: 'my-photo' // 自动补 .jpg 等扩展名 * }); * formData.append('userId', '123'); */ declare function base64ToFormData(base64: string, options?: { key?: string; filename?: string; }): FormData; /** * Creates a flexible currying function with auto-reset and optional trigger condition. * 创建一个灵活的柯里化函数,支持参数累积、自动重置和可选触发条件。 * * @template Args Argument types 参数类型 * @template R Return type 返回值类型 * @param options Options for configuring the currying behavior 配置柯里化行为的选项 * @param options.fn Function to execute after collecting arguments 收集完参数后执行的函数 * @param options.done Optional condition to trigger execution 可选触发条件,返回 true 时立即执行 * @returns A chainable function with `.map`, `.filter`, `.value`, and implicit conversion * 支持 `.map`、`.filter`、`.value` 和隐式转换的可链式函数 * * @example * const sum = currying({ * fn: (...args) => args.reduce((a, b) => a + b, 0), * done: args => args.length >= 3 * }); * const result = sum(1)(2)(3); // auto executes → 6 * * @example * const product = currying({ fn: (...args) => args.reduce((a, b) => a * b, 1) }); * const result = product(2)(3)(4).value(); // manually executes → 24 * * @example * const result = product(1)(2)(3) * .map(x => x * 2) * .filter(x => x > 2) * .value(); // (1, 2, 3) → (2, 4, 6) → (4, 6) → 24 */ declare function currying<Args extends any[], R>(options: { fn: (...args: Args) => R; done?: (args: Args) => boolean; }): ((...args: any[]) => any) & { value: () => R; map: (fn: (v: any) => any) => { (...newArgs: any[]): R | (((...args: any[]) => any) & /*elided*/ any); map(mapper: (v: any) => any): ((...args: any[]) => any) & /*elided*/ any; filter(predicate: (v: any) => boolean): ((...args: any[]) => any) & /*elided*/ any; value(): R; valueOf(): R; toString(): string; }; filter: (fn: (v: any) => boolean) => { (...newArgs: any[]): R | (((...args: any[]) => any) & /*elided*/ any); map(mapper: (v: any) => any): ((...args: any[]) => any) & /*elided*/ any; filter(predicate: (v: any) => boolean): ((...args: any[]) => any) & /*elided*/ any; value(): R; valueOf(): R; toString(): string; }; valueOf: () => R; toString: () => string; }; type Debounced<T extends (...args: any[]) => any, This = any> = { (this: This, ...args: Parameters<T>): Promise<ReturnType<T> | undefined>; cancel: () => void; flush: () => Promise<ReturnType<T> | undefined>; pending: () => boolean; }; type DebouncedSync<T extends (...args: any[]) => any, This = any> = { (this: This, ...args: Parameters<T>): ReturnType<T> | void; cancel: () => void; flush: () => ReturnType<T> | void; pending: () => boolean; }; /** * Creates a debounced version of the provided function. * 创建一个防抖函数,延迟执行直到等待时间结束。 * * @template T - The type of the function to debounce. * @template This - The type of the `this` context for the function. * * @param {T} fn - The original function to debounce. 原始函数。 * @param {number} [delay=500] - The debounce delay in milliseconds. 防抖延迟,单位毫秒,默认 500。 * @returns {Debounced<T, This>} Returns a debounced function with `cancel`, `flush`, and `pending` methods. * 返回防抖函数,附带取消(cancel)、立即执行(flush)和查询等待状态(pending)方法。 * * @example * // 基本用法,普通函数 * const debouncedLog = debounce(function(this: any, message: string) { * console.log(message); * }, 300); * debouncedLog("Hello World"); * * @example * // 在类或对象中使用,this 指向调用者 * const obj = { * prefix: "Log: ", * log: debounce(function(this: typeof obj, msg: string) { * console.log(this.prefix + msg); * }, 200) * }; * obj.log("Test"); // 输出:Log: Test * * @example * // 取消延迟执行 * const fn = debounce(() => console.log("Done"), 1000); * fn(); * fn.cancel(); // 取消执行 * * @example * // 立即执行剩余任务 * const fn2 = debounce(() => console.log("Flush!"), 1000); * fn2(); * fn2.flush(); // 立即执行 */ declare function debounce<T extends (...args: any[]) => any, This = any>(fn: T, delay?: number): Debounced<T, This>; /** * debounced version of a synchronous function. * 同步防抖函数,延迟执行直到等待时间结束。 * * @template T - The type of the function to debounce. * @template This - The type of the `this` context for the function. * * @param {T} fn - The synchronous function to debounce. 要防抖的同步函数。 * @param {number} [delay=500] - Debounce delay in milliseconds, default 500. 防抖延迟时间(毫秒),默认 500。 * @returns {DebouncedSync<T, This>} Returns a debounced function with `cancel`, `flush`, and `pending` methods. 返回带取消、立即执行和状态查询功能的防抖函数。 * * @example * const syncLog = debounceSync(function (this: any, msg: string) { * console.log("Sync:", msg); * }, 300); * syncLog("Hello"); * * @example * const obj = { * prefix: "[Sync] ", * log: debounceSync(function (this: typeof obj, msg: string) { * console.log(this.prefix + msg); * }, 300), * }; * obj.log("Test"); // 输出:[Sync] Test * * @example * const fn = debounceSync(() => console.log("Run"), 500); * fn(); * fn.cancel(); // 取消执行 * * @example * const fn2 = debounceSync(() => console.log("Run later"), 500); * fn2(); * fn2.flush(); // 立即执行 */ declare function debounceSync<T extends (...args: any[]) => any, This = any>(fn: T, delay?: number): DebouncedSync<T, This>; /** * Generate a random verification code string of specified length, with optional custom charset * and the ability to exclude ambiguous characters (like 0/O/1/l). * 生成指定长度的随机验证码字符串,可自定义字符集,并支持排除易混淆字符(如 0/O/1/l)。 * * @param {number} [len=4] - Length of the code. 验证码长度,默认 4。 * @param {Object} [options] - Optional config. 可选配置项。 * @param {string} [options.charset] - Custom charset. 自定义字符集。 * @param {boolean} [options.excludeConfusing=true] - Whether to exclude confusing characters. 是否排除易混淆字符,默认 true。 * @returns {string} Randomly generated verification code. 返回生成的验证码字符串。 * * @example * ```ts * generateVerificationCode(); // e.g., 'a8Z3' * generateVerificationCode(6); // e.g., 'X2a9Lb' * generateVerificationCode(6, { charset: "ABC123" }); // e.g., '1CBAC3' * generateVerificationCode(6, { excludeConfusing: true }); // e.g., 'x7KpT9'(排除了 0/O/l/1) * ``` */ declare function generateVerificationCode(len?: number, options?: { charset?: string; excludeConfusing?: boolean; }): string; type BrowserType = "IE7" | "IE8" | "IE9" | "IE10" | "IE11" | "Edge" | "FireFox" | "Opera" | "Chrome" | "Safari" | null; /** * @description Get browser type based on parsed UA info. * 获取浏览器类型,基于已解析的 UA 信息。 * * @returns {BrowserType} One of the browser types: 'IE7'|'IE8'|'IE9'|'IE10'|'IE11'|'Edge'|'FireFox'|'Opera'|'Chrome'|'Safari' or null. * 返回浏览器类型,可能值为:'IE7'|'IE8'|'IE9'|'IE10'|'IE11'|'Edge'|'FireFox'|'Opera'|'Chrome'|'Safari' 或 null。 * * @example * ```ts * console.log(getBrowserType()); * // Output: 'Chrome' (if user is on Chrome) * ``` */ declare function getBrowserType(): BrowserType; declare function getUA(overrideUA?: string): string; declare function noop(): void; /** * Serializes a flat object into a query string with URL encoding. * 将扁平对象序列化为查询字符串,并进行 URL 编码。 * * @param obj - The flat object to serialize. 要序列化的扁平对象。 * @returns A URL-safe query string. 返回 URL 安全的查询字符串。 * * @example * parseQuery({ name: "Tom", age: 20 }); * // => "name=Tom&age=20" * * @example * parseQuery({ city: "北京", lang: "zh-CN" }); * // => "city=%E5%8C%97%E4%BA%AC&lang=zh-CN" */ declare const parseQuery: (obj: Record<string | number, any>) => string; /** * Serializes an object into a query string using a custom serializer function. * 使用自定义序列化函数将对象转换为查询字符串。 * * @param obj - The object to serialize. 要序列化的对象。 * @param serializer - Function to serialize each key-value pair. 自定义序列化函数。 * @returns A serialized query string. 返回序列化后的查询字符串。 * * @example * parseQueryWith({ a: 1, b: null, c: "test" }, (key, value) => { * if (value == null) return null; * return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; * }); * // => "a=1&c=test" */ declare const parseQueryWith: (obj: Record<string, any>, serializer: (key: string, value: any) => string | null) => string; /** * Serializes a deeply nested object into a query string, supporting objects and arrays. * 深度序列化嵌套对象为查询字符串,支持对象与数组。 * * @param obj - The object to serialize. 要序列化的对象。 * @returns A URL-safe query string. 返回 URL 安全的查询字符串。 * * @example * parseQueryDeep({ * user: { name: "Tom", age: 20 }, * tags: ["ts", "js"], * q: "hello" * }); * // => "user[name]=Tom&user[age]=20&tags[]=ts&tags[]=js&q=hello" */ declare const parseQueryDeep: (obj: Record<string, any>) => string; /** * Serializes a deeply nested object into a query string, * allowing customization of key path structure via `pathBuilder`. * * 使用自定义 pathBuilder 将嵌套对象序列化为查询字符串,灵活控制键路径格式(如 user.name / user_name / user[name])。 * * @param obj - The nested object to serialize. 要序列化的嵌套对象。 * @param pathBuilder - Builds the final key string from path segments. * 用于构建键路径字符串的自定义函数。 * @returns A URL-encoded query string. 返回编码后的查询字符串。 * * @example * parseQueryDeepWith({ user: { name: "Tom" }, tags: ["ts", "js"] }, path => path.join(".")); * // => "user.name=Tom&tags.0=ts&tags.1=js" * * @example * parseQueryDeepWith({ user: { name: "Tom" } }, path => path.join("_")); * // => "user_name=Tom" * * @example * parseQueryDeepWith({ user: { name: "Tom" } }, (path) => { * const [first, ...rest] = path; * return first + rest.map(k => `[${k}]`).join(''); * }); * // => "user[name]=Tom" */ declare const parseQueryDeepWith: (obj: Record<string, any>, pathBuilder: (path: string[]) => string) => string; interface ParsedUA { browser: { name: string | null; version: string | null; majorVersion?: string | null; }; os: { name: string | null; version: string | null; majorVersion?: string | null; }; device: { type: "Mobile" | "Tablet" | "Desktop" | "SmartTV" | "Console" | "Wearable" | "Unknown"; model: string | null; vendor?: string | null; }; engine: { name: string | null; version: string | null; }; originalUA: string; } /** * @description * Parse the UserAgent string into detailed browser, OS, device, and engine info. * 解析 UserAgent 字符串,返回详细的浏览器、操作系统、设备和渲染引擎信息。 * * @param {string} [ua] - Optional UserAgent string, defaults to navigator.userAgent. * - 可选的 UserAgent 字符串,默认使用 navigator.userAgent。 * @returns {ParsedUA} Parsed UserAgent details. * 解析后的 UA 详细信息。 * * @example * ```ts * * const uaInfo = parseUA(); * console.log(uaInfo.browser.name); // e.g. 'Chrome' * console.log(uaInfo.os.name); // e.g. 'Windows' * console.log(uaInfo.device.type); // e.g. 'Desktop' * ``` */ declare function parseUA(ua?: string): ParsedUA; /** * Generate a random integer between lower (inclusive) and upper (exclusive). * 在 lower(含)和 upper(不含)之间生成一个随机整数。 * * @param {number} [lower=0] - The lower bound (inclusive). 最小值(包含)。 * @param {number} [upper=1] - The upper bound (exclusive). 最大值(不包含)。 * @returns {number} A random integer between lower and upper. 返回一个随机整数。 * * @example * ```ts * randomInt(1, 5); // Possible values: 1, 2, 3, 4 * ``` */ declare function randomInt(lower?: number, upper?: number): number; /** * Generate a random float between lower (inclusive) and upper (exclusive). * 在 lower(含)和 upper(不含)之间生成一个随机浮点数。 * * @param {number} [lower=0] - The lower bound (inclusive). 最小值(包含)。 * @param {number} [upper=1] - The upper bound (exclusive). 最大值(不包含)。 * @returns {number} A random float between lower and upper. 返回一个随机浮点数。 * * @example * ```ts * randomFloat(1.5, 5.5); // Possible: 2.347, 3.98, etc. * ``` */ declare function randomFloat(lower?: number, upper?: number): number; type Throttled<T extends (...args: any[]) => any, This = any> = { (this: This, ...args: Parameters<T>): Promise<ReturnType<T> | undefined>; cancel: () => void; flush: () => Promise<ReturnType<T> | undefined>; pending: () => boolean; }; type ThrottledSync<T extends (...args: any[]) => void, This = any> = { (this: This, ...args: Parameters<T>): void; cancel: () => void; flush: () => void; pending: () => boolean; }; /** * Creates a throttled version of the provided async function. * 创建一个节流函数,确保在指定时间间隔内最多执行一次。 * * @template T - 要节流的函数类型 * @template This - 函数中的 this 上下文类型 * * @param {T} fn - 原始函数 * @param {number} [interval=500] - 节流间隔时间(单位:毫秒) * @returns {Throttled<T, This>} 返回一个带 cancel、flush、pending 方法的节流函数 * * @example * // 基本用法 * const throttled = throttle((msg) => console.log(msg), 1000); * throttled("Hi"); throttled("Skip"); // 只打印 "Hi" * * @example * // 使用 flush 强制执行最后一次 * const fn = throttle(() => console.log("Fire!"), 1000); * fn(); fn(); fn.flush(); // 输出两次 */ declare function throttle<T extends (...args: any[]) => any, This = any>(fn: T, interval?: number): Throttled<T, This>; /** * Creates a throttled version of a sync function (no return value). * 创建一个同步节流函数,确保在间隔时间内最多调用一次。 * * @template T - 函数类型 * @template This - this 上下文类型 * * @param {T} fn - 原始函数 * @param {number} [interval=500] - 节流时间(毫秒) * @returns {ThrottledSync<T, This>} 返回节流函数,附带 cancel、flush、pending * * @example * const throttled = throttleSync((msg) => console.log(msg), 1000); * throttled("Hi"); throttled("Skipped"); // 只打印一次 */ declare function throttleSync<T extends (...args: any[]) => void, This = any>(fn: T, interval?: number): ThrottledSync<T, This>; interface ParsedURL { host: string; hostname: string; pathname: string; port: string; protocol: string; origin: string; href: string; search: string; hash: string; query: Record<string, any>; } /** * Parses a URL string into a structured object. * 解析 URL 字符串为结构化对象。 * * @param {string} url - The full URL string to parse. 要解析的完整 URL 字符串。 * @returns {ParsedURL} Parsed URL components. 解析后的 URL 组件对象。 * * @example * urlParse("https://example.com:8080/path?a=1&b=true&b=false&c="); * // => * { * host: "example.com:8080", * hostname: "example.com", * pathname: "/path", * port: "8080", * protocol: "https:", * origin: "https://example.com:8080", * href: "https://example.com:8080/path?a=1&b=true&b=false&c=", * search: "?a=1&b=true&b=false&c=", * hash: "", * query: { * a: 1, * b: ["true", "false"], * c: "" * } * } */ declare function urlParse(url: string): ParsedURL; interface StringifyURLOptions { protocol?: string; hostname: string; port?: string; pathname?: string; query?: Record<string, any>; hash?: string; } /** * Converts a structured URL object into a URL string. * 将结构化 URL 对象转换为 URL 字符串。 * * @param {StringifyURLOptions} options - URL components to stringify. 要序列化的 URL 组件。 * @param {string} [options.protocol] - The protocol (e.g. "https"). 协议(如 https)。 * @param {string} options.hostname - The hostname. 主机名。 * @param {string} [options.port] - The port number. 端口号。 * @param {string} [options.pathname="/"] - The path. 路径,默认为 `/`。 * @param {Record<string, any>} [options.query] - Query parameters as key-value pairs. 查询参数。 * @param {string} [options.hash] - The hash part (e.g. "#top"). 哈希锚点(如 #top)。 * @returns {string} The full URL string. 序列化后的完整 URL 字符串。 * * @example * urlStringify({ * protocol: "https", * hostname: "example.com", * port: "8080", * pathname: "/path", * query: { a: 1, b: true, c: "", d: ["x", "y"] }, * hash: "top" * }); * // => "https://example.com:8080/path?a=1&b=true&c=&d=x&d=y#top" */ declare function urlStringify(options: StringifyURLOptions): string; /** * MathX: Flexible math tool with chainable APIs. * MathX 工具类:提供灵活的数学自定义的精度和舍入方式进行精确计算功能,支持链式调用。 */ declare class MathX { private _value; private _precision; private _rounding; /** * Constructor. * 构造函数。 * @param value - Initial value. 初始值。 * @param precision - Decimal places. 小数位数。 * @param rounding - Rounding mode. 舍入模式。 * @example * const mx = new MathX(1.2345, 2, 'half-up'); */ constructor(value?: number, precision?: number, rounding?: "half-up" | "up" | "down"); /** * Set value. * 设置值。 * @param value - New value. 新值。 * @returns Current instance. 当前实例。 * @example * mx.set(5); */ set(value: number): this; /** * Get current value. * 获取当前值。 * @returns Current value. 当前值。 * @example * mx.value(); // => 5 */ value(): number; /** * Set precision. * 设置小数位数。 * @param digits - Number of decimal places. 小数位数。 * @returns Current instance. 当前实例。 * @example * mx.setPrecision(3); */ setPrecision(digits: number): this; /** * Set rounding mode. * 设置舍入模式。 * @param mode - Rounding mode ('half-up', 'up', 'down'). 舍入模式('half-up'、'up'、'down')。 * @returns Current instance. 当前实例。 * @example * mx.setRounding('up'); */ setRounding(mode: "half-up" | "up" | "down"): this; /** * Clone current instance. * 克隆当前实例。 * @param value - Optional new value. 可选新值。 * @returns New MathX instance. 新的 MathX 实例。 * @example * const clone = mx.clone(10); */ clone(value?: number): MathX; /** * Round helper (internal). * 内部舍入辅助函数。 * @param val - Value to round. 需要舍入的值。 * @returns Rounded value. 舍入后的值。 */ private _round; /** * Add number to current value. * 将当前值与指定数相加。 * * @param num - Number to add. 要相加的数。 * @returns Current instance for chaining. 返回当前实例,可继续链式调用。 * * @example * const mx = new MathX(0.1).setPrecision(2).setRounding('half-up'); * mx.add(0.2).value(); // => 0.3 */ add(num: number): this; /** * Subtract number from current value. * 将当前值与指定数相减。 * * @param num - Number to subtract. 要相减的数。 * @returns Current instance for chaining. 返回当前实例,可继续链式调用。 * * @example * const mx = new MathX(0.3).setPrecision(2).setRounding('half-up'); * mx.subtract(0.1).value(); // => 0.2 */ subtract(num: number): this; /** * Multiply current value by number. * 将当前值与指定数相乘。 * * @param num - Number to multiply. 要相乘的数。 * @returns Current instance for chaining. 返回当前实例,可继续链式调用。 * * @example * const mx = new MathX(0.1).setPrecision(2).setRounding('half-up'); * mx.multiply(0.2).value(); // => 0.02 */ multiply(num: number): this; /** * Divide current value by number. * 将当前值与指定数相除。 * * @param num - Number to divide by. 除数。 * @returns Current instance for chaining. 返回当前实例,可继续链式调用。 * * @example * const mx = new MathX(1).setPrecision(2).setRounding('half-up'); * mx.divide(3).value(); // => 0.33 */ divide(num: number): this; /** * Absolute value. * 取绝对值。 * @returns Current instance. 当前实例。 * @example * mx.set(-5).abs().value(); // => 5 */ abs(): this; /** * Square root. * 开平方。 * @returns Current instance. 当前实例。 * @example * mx.set(9).sqrt().value(); // => 3 */ sqrt(): this; /** * Cube root. * 开立方根。 * @returns Current instance. 当前实例。 * @example * mx.set(8).cbrt().value(); // => 2 */ cbrt(): this; /** * Power. * 幂次运算。 * @param exp - Exponent. 指数。 * @returns Current instance. 当前实例。 * @example * mx.set(2).pow(3).value(); // => 8 */ pow(exp: number): this; /** * Floor. * 向下取整。 * @returns Current instance. 当前实例。 * @example * mx.set(2.7).floor().value(); // => 2 */ floor(): this; /** * Ceil. * 向上取整。 * @returns Current instance. 当前实例。 * @example * mx.set(2.3).ceil().value(); // => 3 */ ceil(): this; /** * Round to nearest integer. * 四舍五入到整数。 * @returns Current instance. 当前实例。 * @example * mx.set(2.5).round().value(); // => 3 */ round(): this; /** * Sign function. * 获取符号(-1, 0, 1)。 * @returns Current instance. 当前实例。 * @example * mx.set(-10).sign().value(); // => -1 */ sign(): this; /** * Convert degrees to radians. * 角度转弧度。 * @returns Current instance. 当前实例。 * @example * mx.set(180).degToRad().value(); // => 3.14 */ degToRad(): this; /** * Convert radians to degrees. * 弧度转角度。 * @returns Current instance. 当前实例。 * @example * mx.set(Math.PI).radToDeg().value(); // => 180 */ radToDeg(): this; /** * Max with other numbers. * 与其他值比较取最大值。 * @param nums - Numbers to compare. 要比较的其他数字。 * @returns Current instance. 当前实例。 * @example * mx.set(5).max(3, 10).value(); // => 10 */ max(...nums: number[]): this; /** * Min with other numbers. * 与其他值比较取最小值。 * @param nums - Numbers to compare. 要比较的其他数字。 * @returns Current instance. 当前实例。 * @example * mx.set(5).min(1, 3).value(); // => 1 */ min(...nums: number[]): this; /** * Sine. * 正弦函数。 * @returns Current instance. 当前实例。 * @example * mx.set(Math.PI / 2).sin().value(); // => 1 */ sin(): this; /** * Cosine. * 余弦函数。 * @returns Current instance. 当前实例。 * @example * mx.set(0).cos().value(); // => 1 */ cos(): this; /** * Tangent. * 正切函数。 * @returns Current instance. 当前实例。 * @example * mx.set(Math.PI / 4).tan().value(); // => 1 */ tan(): this; /** * Arcsine. * 反正弦函数。 * @returns Current instance. 当前实例。 * @example * mx.set(1).asin().radToDeg().value(); // => 90 */ asin(): this; /** * Arccosine. * 反余弦函数。 * @returns Current instance. 当前实例。 * @example * mx.set(0).acos().radToDeg().value(); // => 90 */ acos(): this; /** * Arctangent. * 反正切函数。 * @returns Current instance. 当前实例。 * @example * mx.set(1).atan().radToDeg().value(); // => 45 */ atan(): this; /** * Natural logarithm. * 自然对数。 * @returns Current instance. 当前实例。 * @example * mx.set(Math.E).log().value(); // => 1 */ log(): this; /** * Base-10 logarithm. * 以 10 为底的对数。 * @returns Current instance. 当前实例。 * @example * mx.set(100).log10().value(); // => 2 */ log10(): this; /** * Exponential function. * 指数函数(以 e 为底)。 * @returns Current instance. 当前实例。 * @example * mx.set(1).exp().value(); // => 2.72 */ exp(): this; /** * Convert the current value to exponential notation string. * 将当前值转换为指数计数法字符串。 * @param fractionDigits - Number of digits after the decimal point. 小数点后的位数。 * If omitted, uses as many digits as necessary. 省略时自动决定。 * @returns Exponential notation string. 指数计数法字符串。 * @example * const mx = new MathX(12345); * console.log(mx.toExponential()); // e.g. "1.2345e+4" * console.log(mx.toExponential(2)); // e.g. "1.23e+4" */ toExponential(fractionDigits?: number): string; } /** * Check if an object has a specific property * @param obj - The object to check * @param key - The key to check * @returns True if the object has the property, false otherwise * @example * const obj = { a: 1, b: 2 }; * hasOwn(obj, 'a'); // ✅ true * hasOwn(obj, 'c'); // ❌ false */ declare function hasOwn<T extends object>(obj: T, key: keyof T | (string & {}) | symbol | number): boolean; /** * Retrieves the own property keys of an object, filtered by an optional predicate. * * This function supports both string and symbol keys, and by default only includes * enumerable properties. You can provide a custom predicate to filter keys based on * their name and property descriptor. * * If the input is a primitive value (non-object), it returns an empty array. * * @template T - The type of the input object. * @param {T} obj - The object whose keys are to be retrieved. * @param {(key?: string | symbol, descriptor?: PropertyDescriptor) => boolean} [predicate] - * An optional function to filter keys. It receives each key and its descriptor. * If not provided, only enumerable keys are returned. * @returns {(keyof T)[]} An array of the object's own keys filtered by the predicate. * * @example * const obj = { * a: 1, * b: 2, * get c() { return 3; } * }; * Object.defineProperty(obj, 'd', { * value: 4, * enumerable: false * }); * const sym = Symbol('e'); * obj[sym] = 5; * * // Get only enumerable keys (default) * keys(obj); // ['a', 'b', 'c', Symbol(e)] * * // Get all keys, including non-enumerable * keys(obj, () => true); // ['a', 'b', 'c', 'd', Symbol(e)] * * // Get only non-enumerable keys * keys(obj, (key, desc) => !desc.enumerable); // ['d'] * * // Get only symbol keys * keys(obj, (key) => typeof key === 'symbol'); // [Symbol(e)] */ declare function keys<T extends object>(obj: T, predicate?: (key?: string | symbol, descriptor?: PropertyDescriptor) => boolean): (keyof T)[]; /** * Merges two objects into one. Properties from the second object * will overwrite those from the first object in case of conflicts. * Symbol keys are also supported. * * @template T - The type of the first object * @template U - The type of the second object * @param target - The target object to receive properties * @param source - The source object to copy properties from * @returns A new object with merged properties * * @example * ```ts * const sym = Symbol('id'); * const a = { name: 'Alice', age: 25 }; * const b = { age: 30, [sym]: 123 }; * const result = merge(a, b); * // result: { name: 'Alice', age: 30, [sym]: 123 } * ``` */ declare function merge<T extends object, U extends object>(target: T, source: U): T & U; /** * Recursively deep merges two objects. Properties from the source object * will overwrite those in the target. Arrays are overwritten by default. * Symbol keys are also supported. * * @template T - The type of the first object * @template U - The type of the second object * @param target - The target object to receive properties * @param source - The source object to merge from * @returns A new object deeply merged from target and source * * @example * ```ts * const a = { user: { name: 'Alice', hobbies: [{ sport: 'tennis' }] } }; * const b = { user: { age: 30, hobbies: [{ level: 'pro' }] } }; * const result = mergeDeep(a, b); * // result: { user: { name: 'Alice', age: 30, hobbies: [{ sport: 'tennis', level: 'pro' }] } } * ``` */ declare function mergeDeep<T extends object, U extends object>(target: T, source: U): T & U; type ExistingKeys$1<T> = keyof T & string; /** * @description Creates a new object by omitting the specified keys from the original object. * @param obj The source object * @param keysToOmit An array of keys to omit * @returns A new object without the specified keys * * @example * const user = { name: 'Alice', age: 25, password: 'secret' }; * const safeUser = omit(user, ['password']); * console.log(safeUser); // ✅ { name: 'Alice', age: 25 } */ declare function omit<T extends object, K extends string>(obj: T, keysToOmit: K[]): Omit<T, Extract<K, ExistingKeys$1<T>>>; /** * @description Creates a new object by omitting properties that match the predicate function. * @param obj The source object * @param predicate A function that returns `true` if the property should be omitted * @returns A new object without the properties that match the predicate * * @example * const user = { name: 'Alice', age: null, isActive: true }; * const cleaned = omitBy(user, (value) => value === null); * console.log(cleaned); // ✅ { name: 'Alice', isActive: true } */ declare function omitBy<T extends object>(obj: T, predicate: (value: T[keyof T], key: keyof T) => boolean): Partial<T>; type ExistingKeys<T> = keyof T & string; /** * @description Creates a new object composed of the picked properties. * @param obj The source object * @param keysToPick An array of keys to pick from the source object * @returns A new object containing only the picked keys * * @example * const user = { name: 'Alice', age: 25, password: 'secret' }; * const partialUser = pick(user, ['name', 'age']); * console.log(partialUser); // ✅ { name: 'Alice', age: 25 } */ declare function pick<T extends object, K extends string>(obj: T, keysToPick: readonly K[]): Pick<T, Extract<K, ExistingKeys<T>>>; /** * @description Creates a new object composed of properties that satisfy the predicate function. * @param obj The source object * @param predicate A function invoked with (value, key) that returns `true` to keep the property * @returns A new object with properties that satisfy the predicate * * @example * const user = { name: 'Alice', age: 25, isActive: false }; * const activeProps = pickBy(user, (value) => Boolean(value)); * console.log(activeProps); // ✅ { name: 'Alice', age: 25 } */ declare function pickBy<T extends object>(obj: T, predicate: (value: T[keyof T], key: keyof T) => boolean): Partial<T>; /** * Retrieves the values of an object's own properties, filtered by an optional predicate. * * Supports both string and symbol keys. By default, only enumerable properties are included. * A custom predicate can be provided to control which values are returned based on the key * and property descriptor. * * If the input is a primitive (non-object), an empty array is returned. * * @template T - The type of the input object. * @param {T} obj - The object whose values are to be retrieved. * @param {(key?: string | symbol, descriptor?: PropertyDescriptor) => boolean} [predicate] - * Optional predicate function to filter properties. Receives the key and descriptor. * If omitted, only enumerable values are returned. * @returns {T[keyof T][]} An array of the object's own property values, filtered by the predicate. * * @example * const obj = { * a: 1, * b: 2, * get c() { return 3; } * }; * Object.defineProperty(obj, 'd', { * value: 4, * enumerable: false * }); * const sym = Symbol('e'); * obj[sym] = 5; * * // Get only enumerable values (default) * values(obj); // [1, 2, 3, 5] * * // Get all values, including non-enumerable * values(obj, () => true); // [1, 2, 3, 4, 5] * * // Get only non-enumerable values * values(obj, (key, desc) => !desc.enumerable); // [4] * * // Get only symbol values * values(obj, (key) => typeof key === 'symbol'); // [5] */ declare function values<T extends object>(obj: T, predicate?: (key?: string | symbol, descriptor?: PropertyDescriptor) => boolean): T[keyof T][]; declare const plugins: { readonly email: DefineRegexPlugin<"email">; readonly mobile: DefineRegexPlugin<"mobile">; readonly alpha: DefineRegexPlugin<"alpha">; readonly chinese: DefineRegexPlugin<"chinese">; readonly ipv6: DefineRegexPlugin<"ipv6">; readonly postal: DefineRegexPlugin<"postal">; readonly username: DefineRegexPlugin<"username">; readonly ipv4: DefineRegexPlugin<"ipv4">; readonly IDCard: DefineRegexPlugin<"IDCard">; readonly url: DefineRegexPlugin<"url">; readonly qq: DefineRegexPlugin<"qq">; readonly landline: DefineRegexPlugin<"landline">; readonly number: DefineRegexPlugin<"number">; readonly nonAscii: DefineRegexPlugin<"nonAscii">; readonly nonLatin: DefineRegexPlugin<"nonLatin">; readonly password: DefineRegexPlugin<"password">; readonly html: DefineRegexPlugin<"html">; }; type RuleName = keyof typeof plugins; /** * Class for validating a string against registered rules or regular expressions. */ /** * @description Class for validating a string against registered rules or regular expressions. * @author xiaoqiujun * @date 23/05/2025 * @export * @class Checker */ declare class Checker { /** Input string to be validated */ private input; /** Current validation result */ private result; /** Flag indicating whether the next validation should be negated */ private isNegated; /** * Create a new Checker instance. * @param input The input string to validate. */ constructor(input: string); /** * Apply a rule or regular expression to the input string. * @param rule A registered rule name or a RegExp instance. * @returns The Checker instance for method chaining. * @throws Will throw an error if the rule name is not registered. */ use(rule: RuleName | RegExp | (string & {})): this; /** * Negate the result of the next validation rule. * @returns The Checker instance for method chaining. */ not(): this; /** * Get the final validation result. * @returns `true` if the validation passed, otherwise `false`. */ isValid(): boolean; } /** * @description Class for replacing parts of a string using a rule or regular expression. * @author xiaoqiujun * @date 23/05/2025 * @export * @class Replacer */ declare class Replacer { /** The original input string */ private input; /** The pattern to use for replacement */ private pattern?; /** * Create a new Replacer instance. * @param input The input string to perform replacements on. */ constructor(input: string); /** * Set the rule or regular expression to use for replacement. * @param rule A registered rule name or a RegExp object. * @returns The Replacer instance for method chaining. * @throws Will throw an error if the rule name is not registered. */ use(rule: RuleName | RegExp | (string & {})): this; /** * Perform the replacement operation. * @param replacer A replacement string or a function to transform matches. * @returns The Replacer instance for method chaining. * @throws Will throw an error if no pattern has been defined via `.use()`. */ with(replacer: string | ((match: string) => string)): this; /** * Get the final string after all replacements. * @returns The transformed string. */ result(): string; } type RegexValidateContext<T extends string> = { name: T; pattern: RegExp; input: string; }; interface DefineRegexPlugin<T extends string> { name: T; pattern: RegExp; validate: (ctx: RegexValidateContext<T>) => boolean; } /** * Checker and Replacer tools. */ declare class Regex { private static instance; private constructor(); static getInstance(): Regex; /** * Create a new Checker instance for validating input strings. * * @param input The string to validate. * @returns {Checker} A Checker instance for rule validation. */ checker(input: string): Checker; /** * Create a new Replacer instance for performing regex-based replacements. * * @param input The string to perform replacements on. * @returns {Replacer} A Replacer instance for rule-based replacements. */ replacer(inp