fuc-new/doc/node_modules/@pengzhanbo/utils/dist/index.d.mts
hellcat 6adbc04d4b 1
2025-10-03 17:17:08 +08:00

1358 lines
36 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Type Helpers
*
* @module Types
*/
/**
* Promise, or maybe not
* @category Types
*/
type Awaitable<T> = T | PromiseLike<T>;
/**
* Function
* @category Types
*/
type Fn<T = void> = (...args: any[]) => T;
/**
* Async Function
* @category Types
*/
type AsyncFn<T = void> = (...args: any[]) => Promise<T>;
/**
* The return type of an async function
* @category Types
*/
type AsyncReturnType<T extends AsyncFn> = Awaited<ReturnType<T>>;
/**
* null or whatever
* @category Types
*/
type Nullable<T> = T | null | undefined;
/**
* array or not yet
* @category Types
*/
type Arrayable<T> = T | T[];
/**
* Constructor
* @category Types
*/
type Constructor<T = void> = new (...arg: any[]) => T;
/**
* Infers the element type of an array
* @category Types
*/
type ElementOf<T> = T extends (infer E)[] ? E : never;
/**
* Processing array-type data
*
* 处理数组类型的数据
*
* @module Array
*/
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* 将 `Arrayable<T>` 转换为 `Array<T>`
*
* @category Array
* @example
* ```ts
* toArray(null) // => []
* toArray(undefined) // => []
* toArray([]) // => []
* toArray(1) // => [1]
* ```
*/
declare function toArray<T>(v: Nullable<Arrayable<T>>): Array<T>;
/**
* Unique array
*
* 数组去重
*
* @category Array
* @example
* ```ts
* uniq([1, 1, 2, 2, 3, 3]) // => [1, 2, 3]
* ```
*/
declare function uniq<T>(v: T[]): T[];
/**
* Unique array by a custom equality function
*
* 通过自定义相等函数实现数组去重
*
* @category Array
* @example
* ```ts
* uniqueBy([1, 1, 2, 2, 3, 3], (a, b) => a === b) // => [1, 2, 3]
* ```
*/
declare function uniqueBy<T>(array: T[], equalFn: (a: T, b: T) => boolean): T[];
/**
* Remove value from array
*
* 从数组中移除值
*
* @category Array
*
* @param array - the array
* @param value - the value to remove - 待移除的值
* @returns - if `true`, the value is removed, `false` otherwise.
* - 如果成功移除,返回 `true`, 否则返回 `false`
*
* @example
* ```ts
* const arr = [1, 2, 3]
* remove(arr, 2) // => true
* console.log(arr) // => [1, 3]
* remove(arr, 4) // => false
* ```
*/
declare function remove<T>(array: T[], value: T): boolean;
/**
* Generate a range array of numbers starting from `0`. The `stop` is exclusive.
*
* 从 `0` 开始生成一个数字范围的数组, `stop` 是不包含的。
*
* @category Array
*
* @param stop - the end of the range. 范围结束数字。
*
* @example
* ```ts
* range(5) // => [0, 1, 2, 3, 4]
* ```
*/
declare function range(stop: number): number[];
/**
* Generate a range array of numbers. The `stop` is exclusive.
*
* 生成一个数字范围的数组, `stop` 是不包含的。
*
* @category Array
*
* @param start - the start of the range. 范围开始数字
* @param stop - the end of the range. 范围结束数字
* @param step - the step of the range. 步进
*
* @example
* ```ts
* range(5, 10) // => [5, 6, 7, 8, 9]
* range(5, 10, 2) // => [5, 7, 9]
* ```
*/
declare function range(start: number, stop: number, step?: number): number[];
/**
* Move item in an array
*
* 移动数组中的项
*
* @category Array
*
* @param arr - the array
* @param from - the index of the item to move. 要移动的项的索引
* @param to - the index to move to. 要移动到的索引
* @returns the array with the item moved. 返回移动后的数组
* @example
* ```ts
* move([1, 2, 3], 0, 2) // => [3, 1, 2]
* ```
*/
declare function move<T>(arr: T[], from: number, to: number): T[];
/**
* Shuffle array
*
* 数组洗牌,随机打乱数组中的顺序
*
* @category Array
* @example
* ```ts
* shuffle([1, 2, 3]) // => [1, 3, 2]
* ```
*/
declare function shuffle<T>(array: T[]): T[];
/**
* Sort array
*
* 数组排序
*
* @category Array
* @example
* ```ts
* const arr = [
* { name: 'Mark', age: 20 },
* { name: 'John', age: 18 },
* { name: 'Jack', age: 21 },
* { name: 'Tom', age: 18 },
* ]
* sortBy(arr, (item) => item.age) // => [ { name: 'John', age: 18 }, { name: 'Tom', age: 18 }, { name: 'Mark', age: 20 }, { name: 'Jack', age: 21 } ]
* ```
*/
declare function sortBy<T>(array: T[], cb: (item: T) => number): T[];
/**
* Split array into chunks
*
* 将数组拆分成块
*
* @category Array
*
* @param input - the array
* @param size - the chunk size. 块的大小
*
* @example
* ```ts
* chunk([1, 2, 3, 4, 5], 2) // => [[1, 2], [3, 4], [5]]
* ```
*/
declare function chunk<T>(input: T[], size?: number): T[][];
/**
* Union two arrays
*
* 两个数组的并集
*
* @category Array
*
* @example
* ```ts
* union([1, 2, 3], [2, 4, 5, 6]) // => [1, 2, 3, 4, 5, 6]
* ```
*/
declare function union<T>(a: T[], b: T[]): T[];
/**
* Intersection of two arrays
*
* 两个数组的交集
*
* @category Array
* @example
* ```ts
* intersection([1, 2, 3], [2, 4, 5, 6]) // => [2]
* ```
*/
declare function intersection<T>(firstArr: readonly T[], secondArr: readonly T[]): T[];
/**
* clone data
*
* 克隆数据
*
* @module Clone
*/
/**
* simple clone, use JSON.parse and JSON.stringify
*
* 简单的克隆,使用 JSON.parse 和 JSON.stringify
* @category Clone
*/
declare function simpleClone<T = any>(source: T): T;
/**
* shallow clone, only clone the first level
*
* 浅克隆,只克隆第一层
*
* @category Clone
*/
declare function shallowClone<T = any>(source: T): T;
/**
* Deep Clone.
*
* 深度克隆
*
* @category Clone
*/
declare function deepClone<T = any>(source: T): T;
/**
* Common functions
*
* @module Common
*/
/**
* Asserts that a condition is true
*
* @param condition the condition to assert
* @param message the message to display if the condition is false
*
* @category Common
*/
declare function assert(condition: unknown, message?: string): asserts condition;
/**
* Get the string representation of a value
*
* 获取值的字符串表示
*
* @category Common
*/
declare function toString(s: unknown): string;
/**
* Get type name of a value
*
* 获取值的类型名称
*
* @category Common
* @example
* ```ts
* getTypeName(null) // => 'null'
* getTypeName(undefined) // => 'undefined'
* getTypeName({}) // => 'object'
* ```
*/
declare function getTypeName(s: unknown): string;
/**
* Equal
*
* @module Equal
*/
/**
* Deep equality two values, support array and object
*
* @category Equal
*/
declare function deepEqual(v1: any, v2: any): boolean;
/**
* Base Event
*
* @module Event
*/
/**
* @category Event
*/
declare class BaseEvent {
private _listeners;
constructor();
/**
* Adds a listener to the specified event.
*
* @param event - the event to listen for
* @param listener - the listener function to be called when the event is triggered
* @return
*/
on(event: string, listener: (...args: any[]) => void): void;
/**
* Emits the specified event with the given arguments to all registered listeners.
*
* @param event - the name of the event to emit
* @param args - the arguments to pass to the event listeners
* @return
*/
emit(event: string, ...args: any[]): void;
/**
* Turn off the specified event listener.
*
* @param event - the name of the event to turn off
* @param listener - (optional) the listener function to turn off
*/
off(event: string, listener?: (...args: any[]) => void): void;
/**
* Execute the listener at most once for a particular event.
*
* @param event - the event to listen for
* @param listener - the function to be executed once for the event
*/
once(event: string, listener: (...args: any[]) => void): void;
}
/**
* Function Helpers
*
* @module Function
*/
/**
* noop function
*
* 空函数
*
* @category Function
*/
declare function noop(): void;
/**
* Create a function that can only be called once,
* and repeated calls return the result of the first call
*
* 创建只能被调用一次的函数,重复调用返回第一次调用的结果
*
* @category Function
*/
declare function once<T extends (...args: any[]) => any>(func: T): T;
/**
* call the function
*
* 调用函数
*
* @category Function
*/
declare function invoke<T>(fn: Fn<T>): T;
/**
* call every functions in an array
*
* 调用数组中的每个函数
*
* @category Function
*
* @param fns - an array of functions
*/
declare function invoke(fns: Nullable<Fn>[]): void;
type ComposeFn = (...args: any[]) => any;
type LastArray<T extends any[]> = T extends [...any[], infer U] ? U : Fn;
type FirstArray<T extends any[]> = T extends [infer U, ...any[]] ? U : Fn;
/**
* compose multiple functions, right to left
*
* 组合多个函数,从右到左执行
*
* @category Function
* @example
* ```ts
* const add = (a) => a + 1
* const subtract = (a) => a - 2
* const multiply = (a, b) => a * b
* compose(add, subtract, multiply)(1, 2) => (1 * 2) - 2 + 1 = 1
* ```
*/
declare function compose<T extends ComposeFn[] = ComposeFn[]>(...fns: T): (...args: Parameters<LastArray<T>>) => ReturnType<FirstArray<T>>;
/**
* guard function that returns if val is truthy
*
* 守卫函数,返回 val 是否为真值
*
* @category Function
* @example
* ```ts
* [1, 2, 3, '', false, undefined].filter(isTruthy) // => [1, 2, 3]
* ```
*/
declare function isTruthy(val: unknown): boolean;
/**
* guard function that returns if val is not undefined
*
* 守卫函数,返回 val 不为 undefined
*
* @category Function
* @example
* ```ts
* [1, '', false, undefined].filter(NotUndefined) // => [1, '', false]
* ```
*/
declare function notUndefined(val: unknown): boolean;
/**
* guard function that returns if val is not null or undefined
*
* 守卫函数,返回 val 不为 null 或 undefined
*
* @category Function
* @example
* ```ts
* [1, '', false, null, undefined].filter(notNullish) // => [1, '', false]
* ```
*/
declare function notNullish<T>(val: T | null | undefined): val is NonNullable<T>;
/**
* Checks if the input is defined
* @category Is
*/
declare function isDef<T = any>(v?: T): v is T;
/**
* Checks if the input is a primitive
* @category Is
*/
declare function isPrimitive(v: unknown): v is null | undefined | boolean | number | string | symbol | bigint;
/**
* Checks if the input is a boolean
* @category Is
*/
declare function isBoolean(v: unknown): v is boolean;
/**
* Checks if the input is a function.
* @category Is
*/
declare function isFunction<T extends (...args: any[]) => any>(v: unknown): v is T;
/**
* Checks if the input is a number
* @category Is
*/
declare function isNumber(v: unknown): v is number;
/**
* Checks if the input is a string
* @category Is
*/
declare function isString(v: unknown): v is string;
/**
* Checks if the input is a symbol
* @category Is
*/
declare function isSymbol(v: unknown): v is symbol;
/**
* Checks if the input is an object
* @category Is
*/
declare function isPlainObject(v: unknown): v is Record<PropertyKey, unknown>;
/**
* Checks if the input is an array
* @category Is
*/
declare function isArray<T>(v: unknown): v is T[];
/**
* Checks if the input is undefined
*/
declare function isUndefined(v: unknown): v is undefined;
/**
* Checks if the input is null
* @category Is
*/
declare function isNull(v: unknown): v is null;
/**
* Checks if the input is a regexp
* @category Is
*/
declare function isRegexp(v: unknown): v is RegExp;
/**
* Checks if the input is a date
* @category Is
*/
declare function isDate(v: unknown): v is Date;
/**
* Checks if the input is an empty object
* @category Is
*/
declare function isEmptyObject(v: unknown): boolean;
/**
* Checks if the input is a blob
* @category Is
*/
declare function isBlob(v: unknown): v is Blob;
/**
* Checks if the input is a typed array
* @category Is
*/
declare function isTypedArray(v: unknown): v is Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array;
/**
* Checks if the input is a window
* @category Is
*/
declare function isWindow(v: unknown): boolean;
/**
* Checks if the input is a browser
* @category Is
*/
declare function isBrowser(): boolean;
/**
* Checks if a value is a JSON object.
* @category Is
*/
declare function isJSONObject(obj: unknown): obj is Record<string, any>;
/**
* Checks if a given value is a valid JSON array.
* @category Is
*/
declare function isJSONArray(value: unknown): value is any[];
/**
* Checks if a given value is a valid JSON value.
* @category Is
*/
declare function isJSONValue(value: unknown): value is Record<string, any> | any[] | string | number | boolean | null;
/**
* Math Helpers
*
* @module Math
*/
/**
* Clamp a number between min and max
*
* 返回一个介于最小值和最大值之间的数字
*
* @category Math
*/
declare function clamp(n: number, min: number, max: number): number;
/**
* Check if a number is in range [0, max]
*
* 检查一个数字是否在 [0, max] 范围内
*
* @category Math
*
* @param n - the number
* @param max - the maximum number
* @example
* ```ts
* inRange(5, 10) // => true
* inRange(10, 5) // => false
* ```
*/
declare function inRange(n: number, max: number): boolean;
/**
* Check if a number is in range [min, max]
*
* 检查一个数字是否在 [min, max] 范围内
*
* @category Math
*
* @param n - the number
* @param min - the minimum number
* @param max - the maximum number
* @example
* ```ts
* inRange(5, 0, 10) // => true
* inRange(10, 0, 5) // => false
* ```
*/
declare function inRange(n: number, min: number, max: number): boolean;
/**
* Random number
*
* 返回一个介于 0 和 max 之间的随机数
*
* @category Math
*
* @param max - the maximum number. 最大值
* @param float - (optional) if `true`, returns a floating-point number. 是否返回浮点数
*
* @example
* ```ts
* random(5) // => an integer between 0 and 5
* random(5, true) // => a floating-point number between 0 and 5
* ```
*/
declare function random(max: number, float?: boolean): number;
/**
* Random number between min and max
*
* 返回一个介于 min 和 max 之间的随机数
*
* @category Math
*
* @param min - the minimum number. 最小值
* @param max - the maximum number. 最大值
* @param float - (optional) if `true`, returns a floating-point number. 是否返回浮点数
*
* @example
* ```ts
* random(1, 5) // => an integer between 1 and 5
* random(1, 5, true) // => a floating-point number between 1 and 5
* ```
*/
declare function random(min: number, max: number, float?: boolean): number;
type GenNode<K extends string | number, IsRoot extends boolean> = IsRoot extends true ? `${K}` : `.${K}` | (K extends number ? `[${K}]` | `.[${K}]` : never);
/**
* Object key paths
* @category Types
*/
type ObjectKeyPaths<T extends object, IsRoot extends boolean = true, K extends keyof T = keyof T> = K extends string | number ? GenNode<K, IsRoot> | (T[K] extends object ? `${GenNode<K, IsRoot>}${ObjectKeyPaths<T[K], false>}` : never) : never;
type KeysPaths<T extends string, O extends string = ''> = T extends `${infer R}['${infer K}']${infer Rest}` ? KeysPaths<Rest, `${O extends '' ? O : `${O}.`}${R}.${K}`> : T extends `${infer R}["${infer K}"]${infer Rest}` ? KeysPaths<Rest, `${O extends '' ? O : `${O}.`}${R}.${K}`> : T extends `${infer R}[${infer K}]${infer Rest}` ? KeysPaths<Rest, `${O extends '' ? O : `${O}.`}${R}.${K}`> : T extends '' ? O : `${O extends '' ? O : `${O}.`}${T}`;
/**
* Get a value from an object
* @category Types
*/
type ObjectGet<T extends Record<PropertyKey, any>, P extends string> = KeysPaths<P> extends `${infer R}.${infer Rest}` ? ObjectGet<T[R], Rest> : T[P];
type MergeInsertions<T> = T extends object ? {
[K in keyof T]: MergeInsertions<T[K]>;
} : T;
/**
* Deep merge
* @category Types
*/
type DeepMerge<F, S> = MergeInsertions<{
[K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never;
}>;
/**
* Object Helpers
*
* @module Object
*/
/**
* Check if an object has a non-inherited property
*
* 检查一个对象是否具有非继承属性
*
* @category Object
*/
declare function hasOwn<T>(obj: T, key: keyof any): key is keyof T;
/**
* Freeze an object recursively and its properties
*
* 递归冻结一个对象及其属性
*
* @category Object
*/
declare function deepFreeze<T>(obj: T): T;
/**
* Check if an object has a property
*
* 检查一个对象是否有属性
*
* @category Object
*/
declare function isKeyof<T extends object>(obj: T, key: keyof any): key is keyof T;
/**
* Get a value from an object
*
* 从一个对象中获取一个值
*
* @category Object
* @example
* ```ts
* objectGet({ a: 1 }, 'a') // => 1
* objectGet({ a: { b: 2 } }, 'a.b') // => 2
* objectGet({ a: [{ b: 2 }] }, 'a[0].b') // => 2
* ```
*/
declare function objectGet<T extends Record<PropertyKey, any>, P extends ObjectKeyPaths<T>>(source: T, path: P): ObjectGet<T, P>;
/**
* Map key/value pairs for an object, and construct a new one
*
* 为一个对象映射键值对,并构造一个新对象
*
* @category Object
*
* Transform:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [k.toString().toUpperCase(), v.toString()])
* // { A: '1', B: '2' }
* ```
*
* Swap key/value:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [v, k])
* // { 1: 'a', 2: 'b' }
* ```
*
* Filter keys:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => k === 'a' ? undefined : [k, v])
* // { b: 2 }
* ```
*/
declare function objectMap<K extends string, V, NK extends PropertyKey = K, NV = V>(obj: Record<K, V>, fn: (key: K, value: V) => [NK, NV] | undefined): Record<NK, NV>;
/**
* Strict typed `Object.keys`
*
* @category Object
* @example
* ```ts
* objectKeys({ a: 1, b: 2 }) // => ['a', 'b']
* ```
*/
declare function objectKeys<T extends object>(obj: T): Array<`${keyof T & (string | number | boolean | null | undefined)}`>;
/**
* Strict typed `Object.entries`
*
* @category Object
* @example
* ```ts
* objectEntries({ a: 1, b: 2 }) // => [['a', 1], ['b', 2]]
* ```
*/
declare function objectEntries<T extends object>(obj: T): Array<[keyof T, T[keyof T]]>;
/**
* Creates a new object with specified keys omitted.
*
* 创建一个新对象,省略指定的键。
*
* @category Object
* @example
* ```ts
* omit({ a: 1, b: 2 }, ['a']) // => { b: 2 }
* ```
*/
declare function omit<T extends object = object, K extends keyof T = keyof T>(obj: T, keys: readonly K[]): Omit<T, K>;
/**
* Creates a new object composed of the picked object properties.
*
* 创建一个由所选对象属性组成的新对象。
*
* @category Object
* @example
* ```ts
* pick({ a: 1, b: 2 }, ['a']) // => { a: 1 }
* ```
*/
declare function pick<T extends object = object, K extends keyof T = keyof T>(obj: T, keys: K[]): Pick<T, K>;
/**
* Deep merge
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* 深度合并
*
* 第一个参数是目标对象,其余的是源对象。
* 目标对象将被修改并返回。
*
* @category Object
*/
declare function deepMerge<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Deep merge
*
* Differs from `deepMerge` in that it merges arrays instead of overriding them.
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* 深度合并
*
* 与 `deepMerge` 不同,它合并数组而不是覆盖它们。
*
* 第一个参数是目标对象,其余的是源。
* 目标对象将被修改并返回。
*
* @category Object
*/
declare function deepMergeWithArray<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Promise Helpers
*
* @module Promise
*/
/**
* Sleeps for the given number of milliseconds.
*
* 给定毫秒数睡眠。
* @param ms - the number of milliseconds to sleep. 睡眠的毫秒数
* @param callback - (optional) the function to execute after the sleep. 睡眠完成后执行的函数。
* @returns a promise
*/
declare function sleep(ms: number, callback?: Fn<any>): Promise<void>;
/**
* Executes an array of promises in parallel with a given concurrency. The function
* returns a Promise that resolves with an array containing the resolved values of
* each promise.
* If any promise is rejected, the returned promise will be rejected.
*
* 以指定的并发数并行执行一组 promise。该函数返回一个 promise该承诺解析为一个数组包含每个 promise 的解析值。
* 任意一个 promise 拒绝,返回的 promise 将被拒绝。
*
* @category Promise
*
* @param promises - the array of promises to execute
* @param concurrency - (optional) the maximum number of promises to execute in parallel 最大并发数
*/
declare function promiseParallel(promises: (PromiseLike<any> | (() => PromiseLike<any>))[], concurrency?: number): Promise<any[]>;
/**
* Creates a promise that is resolved with an array of promise settlement results,
* in the same order as the input promises array.
* The returned promise will be fulfilled when all of the input promises have settled,
* either fulfilled or rejected.
*
* 创建一个以输入 promise 数组的结果数组解决的 promise
* 按照输入 promise 数组的相同顺序。
* 当所有输入 promise 都已解决时,返回的 promise将被实现
* 要么实现,要么拒绝。
*
* @category Promise
*
* @param promises - the array of promises to execute
* @param concurrency - (optional) the maximum number of promises to execute in parallel
*/
declare function promiseParallelSettled(promises: (PromiseLike<any> | (() => PromiseLike<any>))[], concurrency?: number): Promise<PromiseSettledResult<any>[]>;
/**
* An error class representing an timeout operation.
* @category Promise
* @augments Error
*/
declare class TimeoutError extends Error {
constructor(message?: string);
}
/**
* Returns a promise that rejects with a `TimeoutError` after a specified delay.
*
* 返回一个 promise该 promise 在指定的延迟时间后拒绝,抛出一个 `TimeoutError`。
*
* @category Promise
* @param ms - the number of milliseconds to wait before rejecting the promise. 超时的毫秒数
* @throws Throws a `TimeoutError` after the specified delay.
* @example
* ```ts
* @example
* ```
* try {
* await timeout(1000); // Timeout exception after 1 second
* } catch (error) {
* console.error(error); // Will log 'The operation was timed out'
* }
* ```
*/
declare function timeout(ms: number): Promise<never>;
/**
* Executes an async function and enforces a timeout.
*
* 执行异步函数, 超时则强制拒绝
*
* @category Promise
* @param run - the async function to execute.
* @param ms - the number of milliseconds to wait before rejecting the promise.
* @returns A promise that resolves with the result of the async function, or rejects with a `TimeoutError` if the function does not resolve within the specified timeout. 一个 promise它将解析为异步函数的结果或者如果在指定超时内函数未解析则拒绝并抛出`TimeoutError`。
* @example
* ```ts
* async function fetchData() {
* const response = await fetch('https://example.com/data');
* return response.json();
* }
*
* try {
* const data = await withTimeout(fetchData, 1000);
* console.log(data); // Logs the fetched data if `fetchData` is resolved within 1 second.
* } catch (error) {
* console.error(error); // Will log 'TimeoutError' if `fetchData` is not resolved within 1 second.
* }
* ```
*/
declare function withTimeout<T>(run: () => Promise<T>, ms: number): Promise<T>;
interface SingletonPromiseReturn<T> {
(): Promise<T>;
/**
* Reset current staled promise.
* Await it to have proper shutdown.
*/
reset: () => Promise<void>;
}
/**
* Create singleton promise function
*
* 创建单例 promise
*
* @category Promise
*/
declare function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
/**
* Create a promise lock
*
* 创建一个 promise 锁
*
* @category Promise
* @example
* ```
* const lock = createPromiseLock()
*
* lock.run(async () => {
* await doSomething()
* })
*
* // in anther context:
* await lock.wait() // it will wait all tasking finished
* ```
*/
declare function createPromiseLock(): {
run: <T = void>(fn: () => Promise<T>) => Promise<T>;
wait: () => Promise<void>;
isWaiting: () => boolean;
clear: () => void;
};
/**
* Promise with `resolve` and `reject` methods of itself
*
* @category Promise
*/
interface ControlledPromise<T = void> extends Promise<T> {
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
}
/**
* Return a Promise with `resolve` and `reject` methods
*
* 返回一个 Promise带有 `resolve` 和 `reject` 方法
*
* @category Promise
* @example
* ```
* const promise = createControlledPromise()
*
* await promise
*
* // in anther context:
* promise.resolve(data)
* ```
*/
declare function createControlledPromise<T>(): ControlledPromise<T>;
/**
* String Helpers
*
* @module String
*/
/**
* Ensure prefix, if str does not start with prefix, it will be added
*
* 确保前缀,如果字符串不以前缀开头,则将添加前缀。
*
* @category String
*
* @example
* ```ts
* ensurePrefix('http://', 'example.com') // => http://example.com
* ensurePrefix('//', '//example.com') // => //example.com
* ```
*/
declare function ensurePrefix(prefix: string, str: string): string;
/**
* Ensure suffix, if str does not end with suffix, it will be added
*
* 确保后缀,如果字符串不以该后缀结尾,则将添加该后缀。
*
* @category String
*
* @example
* ```ts
* ensureSuffix('.com', 'example.com') // => example.com
* ensureSuffix('.com', 'example') // => example.com
* ```
*/
declare function ensureSuffix(suffix: string, str: string): string;
declare const CASE_SPLIT_PATTERN: RegExp;
/**
* Split string into as words array
*
* 将字符串拆分为单词数组
*
* @category String
* @example
* ```ts
* words('helloWorld🚀') // => ['hello', 'world', '🚀']
* ```
*/
declare function words(str: string): string[];
/**
* First letter uppercase, other lowercase
* @category String
* @example
* ```ts
* capitalize('hello') // 'Hello'
* ```
*/
declare function capitalize(s: string): string;
/**
* Convert string to kebab-case
* @category String
*
* @example
* ```ts
* kebabCase('a b c') // => a-b-c
* kebabCase('orderBy') // => order-by
* ```
*/
declare function kebabCase(str: string): string;
/**
* Convert string to snake_case
* @category String
* @example
* ```ts
* snakeCase('a b c') // => a_b_c
* snakeCase('orderBy') // => order_by
* ```
*/
declare function snakeCase(str: string): string;
/**
* Convert string to camelCase
*
* @category String
*
* @example
* ```ts
* camelCase('foo bar') // => fooBar
* camelCase('foo-bar') // => fooBar
* ```
*/
declare function camelCase(str: string): string;
/**
* Convert string to lowercase
* @category String
* @example
* ```ts
* lowerCase('Hello World') // => 'hello world'
* lowerCase('HELLO WORLD') // => 'hello world'
* lowerCase('order-by') // => 'order by'
* ```
*/
declare function lowerCase(str: string): string;
/**
* Convert string to uppercase
* @category String
* @example
* ```ts
* upperCase('Hello World') // => 'HELLO WORLD'
* upperCase('hello world') // => 'HELLO WORLD'
* upperCase('order-by') // => 'ORDER BY'
* ```
*/
declare function upperCase(str: string): string;
/**
* Converts a string to Pascal case.
* @category String
* @example
* ```ts
* pascalCase('foo bar') // => FooBar
* pascalCase('foo-bar') // => FooBar
* ```
*/
declare function pascalCase(str: string): string;
/**
* Converts the characters "&", "<", ">", '"', and "'" in `str` to their corresponding HTML entities.
*
* 将`str`中的字符"&"、"<"、">"、'"'和"'"转换为对应的HTML实体。
*
* @category String
* @example
* ```ts
* escape('<script>alert(1)</script>') // => &lt;script&gt;alert(1)&lt;/script&gt;
* ```
*/
declare function escape(str: string): string;
/**
* Escapes the RegExp special characters "^", "$", "\\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in `str`.
*
* 转义`str`中的正则表达式特殊字符"^"、"$"、"\\"、"."、"*"、"+"、"?"、"("、")"、"["、"]"、"{"、"}"以及"|"。
*
* @category String
* @example
* ```ts
* escapeRegExp('[link](https://sub.domain.com/)'); // '\[link\]\(https://sub\.domain\.com/\)'
* ```
*/
declare function escapeRegExp(str: string): string;
/**
* Converts the HTML entities `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `str` to their corresponding characters.
* It is the inverse of `escape`.
*
* 将`str`中的HTML实体`&amp;`、`&lt;`、`&gt;`、`&quot;`和`&#39;`转换回对应的字符。
* 此操作是`escape`的逆向过程。
*
* @category String
* @example
* ```ts
* unescape('&lt;script&gt;alert(1)&lt;/script&gt;') // => <script>alert(1)</script>
* ```
*/
declare function unescape(str: string): string;
/**
* Throttle Options
* @category Types
*/
interface ThrottleOptions {
/**
* Optional, defaults to false. If noTrailing is true, callback will only execute
* every `delay` milliseconds while the throttled-function is being called. If
* noTrailing is false or unspecified, callback will be executed one final time
* after the last throttled-function call. (After the throttled-function has not
* been called for `delay` milliseconds, the internal counter is reset)
*/
noTrailing?: boolean;
/**
* Optional, defaults to false. If noLeading is false, the first throttled-function
* call will execute callback immediately. If noLeading is true, the first the
* callback execution will be skipped. It should be noted that callback will never
* executed if both noLeading = true and noTrailing = true.
*/
noLeading?: boolean;
/**
* If `debounceMode` is true (at begin), schedule
* `callback` to execute after `delay` ms. If `debounceMode` is false (at end),
* schedule `callback` to execute after `delay` ms.
*/
debounceMode?: boolean;
}
interface CancelOptions {
upcomingOnly?: boolean;
}
interface Cancel {
cancel: (options?: CancelOptions) => void;
}
interface NoReturn<T extends (...args: any[]) => any> {
(...args: Parameters<T>): void;
}
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @category Function
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* throttled-function is executed.
*
* @param options
* An object to configure options.
*
* @return
* A new, throttled, function.
*/
declare function throttle<T extends (...args: any[]) => any>(delay: number, callback: T, options?: ThrottleOptions): NoReturn<T> & Cancel;
/**
* Debounce Options
* @category Types
*/
interface DebounceOptions {
/**
* If atBegin is false or unspecified, callback will only be executed `delay`
* milliseconds after the last debounced-function call. If atBegin is true,
* callback will be executed only at the first debounced-function call. (After
* the throttled-function has not been called for `delay` milliseconds, the
* internal counter is reset).
*/
atBegin?: boolean;
}
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @category Functions
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* debounced-function is executed.
*
* @param options
* An object to configure options.
*
* @return
* A new, debounced function.
*/
declare function debounce<T extends (...args: any[]) => any>(delay: number, callback: T, options?: DebounceOptions): NoReturn<T> & Cancel;
/**
* Recommended time library:
*
* - [dayjs](https://day.js.org/)
* - [date-fns](https://date-fns.org)
*
* @module
*/
/**
* Get current timestamp
* @category Time
*/
declare function timestamp(): number;
/**
* Check if two dates is same day
* @category Time
*/
declare function isSameDay(date1: Date | number | string, date2?: Date | number | string): boolean;
/**
* URL Helpers
*
* @module URL
*/
/**
* Replace all backslashes with forward slashes
*
* 将所有反斜杠替换为正斜杠
*
* @category String
* @example
* ```ts
* slash('foo\\bar') // => foo/bar
* ```
*/
declare function slash(s: string): string;
/**
* Ensure leading slash, if str does not start with slash, it will be added
*
* 确保前缀,如果字符串不以斜杠开头,则将添加斜杠
*
* @category String
* @example
* ```ts
* ensureLeadingSlash('foo/bar') // => /foo/bar
* ```
*/
declare function ensureLeadingSlash(str: string): string;
/**
* Ensure trailing slash, if str does not end with slash, it will be added
*
* 确保后缀,如果字符串不以斜杠结尾,则将添加斜杠
*
* @category String
* @example
* ```ts
* ensureTrailingSlash('/foo/bar') // => /foo/bar/
* ```
*/
declare function ensureTrailingSlash(str: string): string;
/**
* Remove leading slash, if str starts with slash, it will be removed
*
* 删除斜杆前缀,如果字符串以斜杠开头,则将删除
*
* @category String
* @example
* ```ts
* removeLeadingSlash('/foo/bar') // => foo/bar
* ```
*/
declare function removeLeadingSlash(str: string): string;
/**
* Remove trailing slash, if str ends with slash, it will be removed
*
* 删除斜杆后缀,如果字符串以斜杠结尾,则将删除
*
* @category String
* @example
* ```ts
* removeTrailingSlash('/foo/bar/') // => /foo/bar
* ```
*/
declare function removeTrailingSlash(str: string): string;
/**
* Check if url is http
* @category URL
*/
declare function isHttp(url: string): boolean;
/**
* Check if url is valid
* @category URL
*/
declare function isUrl(url: string): boolean;
/**
* combines urls
* @category URL
* @example
* ```ts
* combineURLs('http://example.com', 'foo', 'bar') // => http://example.com/foo/bar
* combineURLs('//example.com', '/foo') // => //example.com/foo
* combineURLs('/foo', 'bar', 'index.html') // => /foo/bar/index.html
* ```
*/
declare function combineURLs(baseUrl: string, ...urls: string[]): string;
/**
* Parse protocol from url
*
* @category URL
* @example
* ```ts
* parseProtocol('http://example.com') // => http
* parseProtocol('mailto:user@example.com') // => mailto
* ```
*/
declare function parseProtocol(url: string): string;
export { BaseEvent, CASE_SPLIT_PATTERN, TimeoutError, assert, camelCase, capitalize, chunk, clamp, combineURLs, compose, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepClone, deepEqual, deepFreeze, deepMerge, deepMergeWithArray, ensureLeadingSlash, ensurePrefix, ensureSuffix, ensureTrailingSlash, escape, escapeRegExp, getTypeName, hasOwn, inRange, intersection, invoke, isArray, isBlob, isBoolean, isBrowser, isDate, isDef, isEmptyObject, isFunction, isHttp, isJSONArray, isJSONObject, isJSONValue, isKeyof, isNull, isNumber, isPlainObject, isPrimitive, isRegexp, isSameDay, isString, isSymbol, isTruthy, isTypedArray, isUndefined, isUrl, isWindow, kebabCase, lowerCase, move, noop, notNullish, notUndefined, objectEntries, objectGet, objectKeys, objectMap, omit, once, parseProtocol, pascalCase, pick, promiseParallel, promiseParallelSettled, random, range, remove, removeLeadingSlash, removeTrailingSlash, shallowClone, shuffle, simpleClone, slash, sleep, snakeCase, sortBy, throttle, timeout, timestamp, toArray, toString, unescape, union, uniq, uniqueBy, upperCase, withTimeout, words };
export type { Arrayable, AsyncFn, AsyncReturnType, Awaitable, Constructor, ControlledPromise, DebounceOptions, ElementOf, Fn, Nullable, SingletonPromiseReturn, ThrottleOptions };