funtool
Version:
A modern, efficient, and modular JavaScript utility library designed to enhance developer productivity.
637 lines (619 loc) • 23.9 kB
TypeScript
/**
* 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;
export { ObjectId, awaitTo, base64ToBlob, base64ToFormData, currying, debounce, debounceSync, generateVerificationCode, getBrowserType, getUA, noop, parseQuery, parseQueryDeep, parseQueryDeepWith, parseQueryWith, parseUA, randomFloat, randomInt, throttle, throttleSync, urlParse, urlStringify };