@cloudcome/utils-core 0.0.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/LICENSE +21 -0
- package/package.json +277 -6
- package/src/array.ts +312 -0
- package/src/async.ts +379 -0
- package/src/base64.ts +20 -0
- package/src/cache.ts +146 -0
- package/src/color/contrast.ts +20 -0
- package/src/color/distance.ts +28 -0
- package/src/color/helpers.ts +23 -0
- package/src/color/hex-hsl.ts +11 -0
- package/src/color/hex-hsv.ts +28 -0
- package/src/color/hex-hwb.ts +31 -0
- package/src/color/hex-rgb.ts +39 -0
- package/src/color/hsl-lighten.ts +15 -0
- package/src/color/hsv-brighten.ts +17 -0
- package/src/color/luminance.ts +17 -0
- package/src/color/mix.ts +26 -0
- package/src/color/rgb-hsl.ts +53 -0
- package/src/color/rgb-hsv.ts +52 -0
- package/src/color/rgb-hwb.ts +56 -0
- package/src/color/rgb-lab.ts +33 -0
- package/src/color/rgb-whiter.ts +22 -0
- package/src/color/rgb-xyz.ts +62 -0
- package/src/color/types.ts +65 -0
- package/src/color/xyz-lab.ts +54 -0
- package/src/color.ts +19 -0
- package/src/crypto/md5.mjs +357 -0
- package/src/crypto/sha1.mjs +300 -0
- package/src/crypto/sha256.mjs +310 -0
- package/src/crypto/sha512.mjs +459 -0
- package/src/crypto.ts +60 -0
- package/src/date/const.ts +6 -0
- package/src/date/core.ts +162 -0
- package/src/date/days.ts +51 -0
- package/src/date/is.ts +186 -0
- package/src/date/relative.ts +92 -0
- package/src/date/start-end.ts +246 -0
- package/src/date/timezone.ts +220 -0
- package/src/date/weeks.ts +100 -0
- package/src/date.ts +8 -0
- package/src/dict.ts +1 -0
- package/src/dts/global.d.ts +27 -0
- package/src/easing.ts +166 -0
- package/src/emitter.ts +117 -0
- package/src/enum.ts +171 -0
- package/src/env.ts +62 -0
- package/src/error.ts +31 -0
- package/src/exception.ts +68 -0
- package/src/fn.ts +197 -0
- package/src/index.ts +1 -0
- package/src/number.ts +236 -0
- package/src/object/each.ts +56 -0
- package/src/object/get-set.ts +273 -0
- package/src/object/is.ts +128 -0
- package/src/object/merge.ts +180 -0
- package/src/object/process.ts +80 -0
- package/src/object.ts +5 -0
- package/src/path.ts +188 -0
- package/src/promise.ts +111 -0
- package/src/qs.ts +119 -0
- package/src/regexp.ts +156 -0
- package/src/string.ts +146 -0
- package/src/time/from.ts +57 -0
- package/src/time/to.ts +106 -0
- package/src/time.ts +2 -0
- package/src/timer.ts +226 -0
- package/src/tree.ts +394 -0
- package/src/type.ts +197 -0
- package/src/types.ts +78 -0
- package/src/unique.ts +77 -0
- package/src/url.ts +93 -0
- package/src/version.ts +71 -0
- package/test/array.test.ts +332 -0
- package/test/async-real.test.ts +39 -0
- package/test/async.test.ts +375 -0
- package/test/base64.test.ts +32 -0
- package/test/cache.test.ts +83 -0
- package/test/color.test.ts +163 -0
- package/test/crypto.test.ts +34 -0
- package/test/date-tz.test.ts +206 -0
- package/test/date.test.ts +353 -0
- package/test/easing.test.ts +33 -0
- package/test/emitter.test.ts +71 -0
- package/test/enum.test.ts +113 -0
- package/test/env.test.ts +69 -0
- package/test/error.test.ts +58 -0
- package/test/exception.test.ts +43 -0
- package/test/fn.test.ts +263 -0
- package/test/helpers.ts +23 -0
- package/test/index.test.ts +6 -0
- package/test/number.test.ts +213 -0
- package/test/object.test.ts +309 -0
- package/test/path.test.ts +156 -0
- package/test/promise.test.ts +199 -0
- package/test/qs.test.ts +79 -0
- package/test/regexp.test.ts +97 -0
- package/test/string.test.ts +150 -0
- package/test/time.test.ts +214 -0
- package/test/timer.test.ts +114 -0
- package/test/tree.test.ts +348 -0
- package/test/type.test.ts +226 -0
- package/test/unique.test.ts +71 -0
- package/test/url.test.ts +136 -0
- package/test/version.test.ts +52 -0
- package/tsconfig.json +31 -0
- package/vite.config.mts +114 -0
package/src/enum.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import type { AnyObject, MergeIntersection, UnionToIntersection, UnionToTuple } from './types';
|
|
2
|
+
|
|
3
|
+
export type EnumKey = string;
|
|
4
|
+
export type EnumValue = number | string;
|
|
5
|
+
export type EnumMetaAppend = {
|
|
6
|
+
key?: string;
|
|
7
|
+
value?: string | number;
|
|
8
|
+
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
|
9
|
+
[key: string]: any;
|
|
10
|
+
};
|
|
11
|
+
export type EnumMeta<A extends EnumMetaAppend> = A & {
|
|
12
|
+
value: EnumValue;
|
|
13
|
+
};
|
|
14
|
+
export type EnumDescription<A extends EnumMetaAppend> = Record<EnumKey, EnumMeta<A>>;
|
|
15
|
+
|
|
16
|
+
const enumError = Symbol('enumKeyError');
|
|
17
|
+
|
|
18
|
+
type _StartWithDollarSign<T extends string> = T extends `$${infer R}` ? R : never;
|
|
19
|
+
|
|
20
|
+
type _CheckDefinition<O extends AnyObject> = {
|
|
21
|
+
// [K in keyof O & string]: K extends Capitalize<K> ? O[K] : `错误:枚举键名 ${K} 必须大写字母开头`;
|
|
22
|
+
[K in keyof O & string]: K extends Capitalize<K>
|
|
23
|
+
? K extends `$${infer R}`
|
|
24
|
+
? O[K] & { [enumError]: `错误:枚举键名 ${K} 不能以 $ 符号开头` }
|
|
25
|
+
: O[K]
|
|
26
|
+
: O[K] & { [enumError]: `错误:枚举键名 ${K} 必须以大写字母开头` };
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
type _ToOriginDefProp<T extends AnyObject> = {
|
|
30
|
+
[K in keyof T as `$${K & string}`]: MergeIntersection<T[K] & { readonly key: K }>;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
type _KVRecord<T> = T extends Record<string, AnyObject>
|
|
34
|
+
? {
|
|
35
|
+
readonly [K in keyof T]: T[K]['value'];
|
|
36
|
+
}
|
|
37
|
+
: never;
|
|
38
|
+
|
|
39
|
+
type _VKRecord<T> = T extends Record<string, AnyObject>
|
|
40
|
+
? MergeIntersection<
|
|
41
|
+
UnionToIntersection<
|
|
42
|
+
{
|
|
43
|
+
[K in keyof T]: {
|
|
44
|
+
[P in keyof T[K] as P extends 'value' ? T[K][P] & (string | number) : never]: K;
|
|
45
|
+
};
|
|
46
|
+
}[keyof T]
|
|
47
|
+
>
|
|
48
|
+
>
|
|
49
|
+
: never;
|
|
50
|
+
|
|
51
|
+
export type EnumExpose<A extends EnumMetaAppend, E extends EnumDescription<A>> = _ToOriginDefProp<E> &
|
|
52
|
+
_KVRecord<E> & {
|
|
53
|
+
readonly definition: E;
|
|
54
|
+
readonly descriptions: MergeIntersection<A & { key: keyof E }>[];
|
|
55
|
+
readonly keys: UnionToTuple<keyof E>;
|
|
56
|
+
readonly length: UnionToTuple<keyof E>['length'];
|
|
57
|
+
readonly values: UnionToTuple<E[keyof E]['value']>;
|
|
58
|
+
readonly kvRecord: _KVRecord<E>;
|
|
59
|
+
readonly vkRecord: _VKRecord<E>;
|
|
60
|
+
toKeyRecord: <P extends keyof A>(prop: P) => Record<keyof E, A[P]>;
|
|
61
|
+
toValueRecord: <P extends keyof A>(prop: P) => Record<E[keyof E]['value'], A[P]>;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 定义一个枚举类型,如果需要类型提示,需要使用 declareEnum 函数定义枚举。
|
|
66
|
+
* @template A - 枚举元数据附加类型,扩展自 EnumMetaAppend
|
|
67
|
+
* @template E - 枚举描述类型,键为枚举键名,值为枚举元数据
|
|
68
|
+
* @param {_CheckDefinition<E>} definition - 枚举定义对象
|
|
69
|
+
* @returns {EnumExpose<A, E>} 返回枚举的完整暴露对象
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* const Status = defineEnum({
|
|
73
|
+
* Pending: { value: 0, label: '待处理' },
|
|
74
|
+
* Approved: { value: 1, label: '已批准' }
|
|
75
|
+
* });
|
|
76
|
+
* ```
|
|
77
|
+
*
|
|
78
|
+
* @property {E} definition - 原始枚举定义对象
|
|
79
|
+
* @property {Array<MergeIntersection<A & { key: keyof E }>>} descriptions - 枚举项的完整描述数组
|
|
80
|
+
* @property {UnionToTuple<keyof E>} keys - 枚举键名的元组
|
|
81
|
+
* @property {"UnionToTuple<keyof E>[\"length\"]"} length - 枚举项的数量
|
|
82
|
+
* @property {UnionToTuple<E[keyof E]["value"]>} values - 枚举值的元组
|
|
83
|
+
* @property {Record<keyof E, E[keyof E]["value"]>} kvRecord - 键到值的映射记录
|
|
84
|
+
* @property {Record<E[keyof E]["value"], E[keyof E]>} vkRecord - 值到键的映射记录
|
|
85
|
+
* @property {function} toKeyRecord - 根据属性名创建键到属性值的映射记录
|
|
86
|
+
* @property {function} toValueRecord - 根据属性名创建值到属性值的映射记录
|
|
87
|
+
*/
|
|
88
|
+
function defineEnum<A extends EnumMetaAppend, const E extends EnumDescription<A>>(
|
|
89
|
+
definition: _CheckDefinition<E>,
|
|
90
|
+
): EnumExpose<A, E> {
|
|
91
|
+
const keys = Object.keys(definition);
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
...[...Object.entries(definition)].reduce((acc, [key, dfn]) => {
|
|
95
|
+
if (key[0].toUpperCase() !== key[0]) {
|
|
96
|
+
throw new Error(`错误:枚举键名 ${key} 必须以大写字母开头`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (key.startsWith('$')) {
|
|
100
|
+
throw new Error(`错误:枚举键名 ${key} 不能以 $ 符号开头`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// @ts-ignore
|
|
104
|
+
acc[key] = dfn.value;
|
|
105
|
+
// @ts-ignore
|
|
106
|
+
acc[`$${key}`] = { key, ...dfn };
|
|
107
|
+
return acc;
|
|
108
|
+
}, {}),
|
|
109
|
+
definition,
|
|
110
|
+
descriptions: keys.map((key) => ({
|
|
111
|
+
key,
|
|
112
|
+
...definition[key],
|
|
113
|
+
})),
|
|
114
|
+
keys,
|
|
115
|
+
length: keys.length,
|
|
116
|
+
values: keys.map((key) => definition[key as keyof E].value),
|
|
117
|
+
kvRecord: keys.reduce((acc, key) => {
|
|
118
|
+
// @ts-ignore
|
|
119
|
+
acc[key] = definition[key].value;
|
|
120
|
+
return acc;
|
|
121
|
+
}, {}),
|
|
122
|
+
vkRecord: keys.reduce((acc, key) => {
|
|
123
|
+
// @ts-ignore
|
|
124
|
+
acc[definition[key].value] = key;
|
|
125
|
+
return acc;
|
|
126
|
+
}, {}),
|
|
127
|
+
toKeyRecord<P extends keyof A>(prop: P) {
|
|
128
|
+
return keys.reduce((acc, key) => {
|
|
129
|
+
// @ts-ignore
|
|
130
|
+
acc[key] = definition[key][prop];
|
|
131
|
+
return acc;
|
|
132
|
+
}, {});
|
|
133
|
+
},
|
|
134
|
+
toValueRecord<P extends keyof A>(prop: P) {
|
|
135
|
+
return keys.reduce(
|
|
136
|
+
(acc, key) => {
|
|
137
|
+
// @ts-ignore
|
|
138
|
+
acc[definition[key].value] = definition[key][prop];
|
|
139
|
+
return acc;
|
|
140
|
+
},
|
|
141
|
+
{} as Record<E[keyof E]['value'], A[P]>,
|
|
142
|
+
);
|
|
143
|
+
},
|
|
144
|
+
} as unknown as EnumExpose<A, E>;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* 声明一个枚举工厂函数
|
|
149
|
+
* @template A - 枚举元数据附加类型,扩展自 EnumMetaAppend
|
|
150
|
+
* @returns {Object} 返回包含 define 方法的对象
|
|
151
|
+
*
|
|
152
|
+
* @property {function} define - 定义枚举的函数
|
|
153
|
+
* @template E - 枚举描述类型
|
|
154
|
+
* @param {_CheckDefinition<E>} definition - 枚举定义对象
|
|
155
|
+
* @returns {EnumExpose<A, E>} 返回枚举的完整暴露对象
|
|
156
|
+
* @example
|
|
157
|
+
* ```typescript
|
|
158
|
+
* const createStatusEnum = declareEnum<{ label: string }>();
|
|
159
|
+
* const Status = createStatusEnum.define({
|
|
160
|
+
* Pending: { value: 0, label: '待处理' },
|
|
161
|
+
* Approved: { value: 1, label: '已批准' }
|
|
162
|
+
* });
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
export function declareEnum<A extends EnumMetaAppend>() {
|
|
166
|
+
return {
|
|
167
|
+
define<const E extends EnumDescription<A>>(definition: _CheckDefinition<E>): EnumExpose<A, E> {
|
|
168
|
+
return defineEnum(definition);
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
}
|
package/src/env.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { isNullish } from './type';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 判断当前环境是否为浏览器环境
|
|
5
|
+
* @returns 如果是浏览器环境返回 true,否则返回 false
|
|
6
|
+
*/
|
|
7
|
+
export function isBrowser() {
|
|
8
|
+
if (IS_TEST) return TEST_MOCK.IS_BROWSER || false;
|
|
9
|
+
|
|
10
|
+
return typeof window !== 'undefined' && typeof document !== 'undefined';
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 判断当前环境是否为 Node.js 环境
|
|
15
|
+
* @returns 如果是 Node.js 环境返回 true,否则返回 false
|
|
16
|
+
*/
|
|
17
|
+
export function isNode() {
|
|
18
|
+
if (IS_TEST) return TEST_MOCK.IS_NODE || false;
|
|
19
|
+
|
|
20
|
+
return typeof process !== 'undefined' && !isNullish(process.versions) && !isNullish(process.versions.node);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 判断当前环境是否为 Web Worker 环境
|
|
25
|
+
* @returns 如果是 Web Worker 环境返回 true,否则返回 false
|
|
26
|
+
* @remarks
|
|
27
|
+
* 使用 @ts-ignore 忽略 self 的类型检查,因为 self 在 Web Worker 中可用但在其他环境中可能未定义
|
|
28
|
+
*/
|
|
29
|
+
export function isWorker() {
|
|
30
|
+
// @ts-ignore
|
|
31
|
+
return typeof self !== 'undefined' && self.importScripts != null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 判断当前操作系统是否为 macOS
|
|
36
|
+
* @returns 如果是 macOS 返回 true,否则返回 false
|
|
37
|
+
* @remarks
|
|
38
|
+
* 在浏览器环境中通过 navigator.platform 检测,在 Node.js 环境中通过 process.platform 检测
|
|
39
|
+
*/
|
|
40
|
+
export function isMacOS() {
|
|
41
|
+
return isBrowser() ? /^mac/i.test(navigator.platform) : isNode() ? /^darwin/i.test(process.platform) : false;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 判断当前操作系统是否为 Linux
|
|
46
|
+
* @returns 如果是 Linux 返回 true,否则返回 false
|
|
47
|
+
* @remarks
|
|
48
|
+
* 在浏览器环境中通过 navigator.platform 检测,在 Node.js 环境中通过 process.platform 检测
|
|
49
|
+
*/
|
|
50
|
+
export function isLinux() {
|
|
51
|
+
return isBrowser() ? /^linux/i.test(navigator.platform) : isNode() ? /^linux/i.test(process.platform) : false;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 判断当前操作系统是否为 Windows
|
|
56
|
+
* @returns 如果是 Windows 返回 true,否则返回 false
|
|
57
|
+
* @remarks
|
|
58
|
+
* 在浏览器环境中通过 navigator.platform 检测,在 Node.js 环境中通过 process.platform 检测
|
|
59
|
+
*/
|
|
60
|
+
export function isWindows() {
|
|
61
|
+
return isBrowser() ? /^win/i.test(navigator.platform) : isNode() ? /^win/i.test(process.platform) : false;
|
|
62
|
+
}
|
package/src/error.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { isError, isNullish } from './type';
|
|
2
|
+
import type { AnyObject } from './types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 标准化处理 Error 对象,适用于 try-catch
|
|
6
|
+
* @param throwError 接收抛出的错误字符串或者 Error 对象或字符串
|
|
7
|
+
* @returns {Error}
|
|
8
|
+
* @example
|
|
9
|
+
* const error = errorNormalize('这是一个错误');
|
|
10
|
+
* console.log(error.message); // 输出: 这是一个错误
|
|
11
|
+
*/
|
|
12
|
+
export function errorNormalize<E extends Error | unknown = unknown>(throwError: E) {
|
|
13
|
+
return (
|
|
14
|
+
isError(throwError) ? throwError : new Error(String(isNullish(throwError) ? '' : throwError))
|
|
15
|
+
) as E extends Error ? E : Error;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 分配对象到 Error 对象上,适用于扩展 Error 实例,不影响原型和构造函数
|
|
20
|
+
* @param {Error} error
|
|
21
|
+
* @param {E} source
|
|
22
|
+
* @returns {Error & E}
|
|
23
|
+
* @example
|
|
24
|
+
* const error = new Error('原始错误');
|
|
25
|
+
* const extendedError = errorAssign(error, { code: 404, message: '未找到资源' });
|
|
26
|
+
* console.log(extendedError.code); // 输出: 404
|
|
27
|
+
* console.log(extendedError.message); // 输出: 未找到资源
|
|
28
|
+
*/
|
|
29
|
+
export function errorAssign<E extends AnyObject>(error: Error, source: E): Error & E {
|
|
30
|
+
return Object.assign(error, source) as Error & E;
|
|
31
|
+
}
|
package/src/exception.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { objectDefaults } from './object';
|
|
2
|
+
import type { AnyObject } from './types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 构建异常选项
|
|
6
|
+
*/
|
|
7
|
+
export type BuildExceptionOptions = {
|
|
8
|
+
/**
|
|
9
|
+
* 自定义错误消息格式函数
|
|
10
|
+
* @param name 错误名称
|
|
11
|
+
* @param message 原始错误消息
|
|
12
|
+
* @returns 格式化后的错误消息
|
|
13
|
+
* @example
|
|
14
|
+
* (name, message) => `${name}::${message}`
|
|
15
|
+
*/
|
|
16
|
+
format?: (name: string, message: string) => string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 默认的异常构建选项
|
|
21
|
+
*/
|
|
22
|
+
const defaults: BuildExceptionOptions = {
|
|
23
|
+
/**
|
|
24
|
+
* 默认消息格式函数
|
|
25
|
+
* @default (name, message) => `[${name}] ${message}`
|
|
26
|
+
*/
|
|
27
|
+
format: (name, message) => `[${name}] ${message}`,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 构建自定义异常类
|
|
32
|
+
* @template T 额外属性的类型
|
|
33
|
+
* @param name 异常类名称
|
|
34
|
+
* @param options 构建选项
|
|
35
|
+
* @returns 自定义异常类
|
|
36
|
+
* @example
|
|
37
|
+
* const MyException = buildException<{ code: number }>('MyException');
|
|
38
|
+
* const err = new MyException('error', { code: 404 });
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* const SimpleException = buildException('SimpleException');
|
|
42
|
+
* const err = new SimpleException('error', undefined);
|
|
43
|
+
*/
|
|
44
|
+
export function buildException<T = void>(name: string, options?: BuildExceptionOptions) {
|
|
45
|
+
const { format } = objectDefaults(options || {}, defaults) as Required<BuildExceptionOptions>;
|
|
46
|
+
|
|
47
|
+
return class extends Error {
|
|
48
|
+
constructor(message: string, extra: T) {
|
|
49
|
+
super(format(name, message));
|
|
50
|
+
this.name = name;
|
|
51
|
+
Object.assign(this, extra);
|
|
52
|
+
}
|
|
53
|
+
} as unknown as {
|
|
54
|
+
new (message: string, extra: T): Error & T;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// const MyException = buildException<{ foo: string; bar: number }>('MyException: ');
|
|
59
|
+
// const myException = new MyException('bar', { foo: '1', bar: 1 });
|
|
60
|
+
// myException.foo;
|
|
61
|
+
// myException.bar;
|
|
62
|
+
// myException.name;
|
|
63
|
+
// myException.message;
|
|
64
|
+
// myException.stack;
|
|
65
|
+
// myException.cause;
|
|
66
|
+
|
|
67
|
+
// const MyException2 = buildException('MyException2: ');
|
|
68
|
+
// const myException2 = new MyException2('bar');
|
package/src/fn.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { isNumber } from './type';
|
|
2
|
+
import type { AnyFunction } from './types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 一个空操作函数,不执行任何操作。
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* fnNoop(); // 不执行任何操作
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export function fnNoop() {
|
|
13
|
+
//
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 防抖函数的配置选项。
|
|
18
|
+
*/
|
|
19
|
+
export type TDebounceOptions = {
|
|
20
|
+
/**
|
|
21
|
+
* 等待时间(毫秒)。
|
|
22
|
+
*/
|
|
23
|
+
wait: number;
|
|
24
|
+
/**
|
|
25
|
+
* 是否在等待开始时立即执行一次
|
|
26
|
+
* @default false
|
|
27
|
+
*/
|
|
28
|
+
leading?: boolean;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 创建一个防抖函数,该函数会在指定的等待时间后执行,如果在等待时间内再次调用,则重新计时。
|
|
33
|
+
*
|
|
34
|
+
* @param fn - 需要防抖的函数。
|
|
35
|
+
* @param wait - 等待时间(毫秒)或包含 `wait` 和 `leading` 选项的对象。
|
|
36
|
+
* @returns 返回一个防抖函数,该函数具有 `cancel` 方法,用于取消防抖操作。
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```typescript
|
|
40
|
+
* const debouncedFn = fnDebounce(() => {
|
|
41
|
+
* console.log('Debounced!');
|
|
42
|
+
* }, 100);
|
|
43
|
+
*
|
|
44
|
+
* debouncedFn(); // 不会立即执行
|
|
45
|
+
* debouncedFn(); // 重新计时
|
|
46
|
+
* debouncedFn.cancel(); // 取消防抖操作
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export function fnDebounce<F extends AnyFunction>(fn: F, wait: number | TDebounceOptions) {
|
|
50
|
+
const options: TDebounceOptions = isNumber(wait) ? { wait } : wait;
|
|
51
|
+
let canceled = false;
|
|
52
|
+
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
|
53
|
+
let timer: any;
|
|
54
|
+
let leading = false;
|
|
55
|
+
|
|
56
|
+
const debounced = function (this: unknown, ...args: Parameters<F>) {
|
|
57
|
+
if (canceled) return;
|
|
58
|
+
|
|
59
|
+
// 第一次执行
|
|
60
|
+
if (options.leading && !leading) {
|
|
61
|
+
leading = true;
|
|
62
|
+
fn.apply(this, args);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 最后一次执行
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
timer = setTimeout(() => {
|
|
69
|
+
if (canceled) return;
|
|
70
|
+
|
|
71
|
+
fn.apply(this, args);
|
|
72
|
+
}, options.wait);
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
debounced.cancel = () => {
|
|
76
|
+
clearTimeout(timer);
|
|
77
|
+
canceled = true;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
return debounced;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export type TThrottleOptions = {
|
|
84
|
+
/**
|
|
85
|
+
* 等待时间(毫秒)。
|
|
86
|
+
*/
|
|
87
|
+
wait: number;
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 是否在第一次调用时立即执行
|
|
91
|
+
* @default false
|
|
92
|
+
*/
|
|
93
|
+
leading?: boolean;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 是否在调用结束后等待一段时间再执行
|
|
97
|
+
* @default false
|
|
98
|
+
*/
|
|
99
|
+
trailing?: boolean;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 创建一个节流函数,该函数会在指定的等待时间内最多执行一次,如果在等待时间内再次调用,则忽略后续调用。
|
|
104
|
+
*
|
|
105
|
+
* @param fn - 需要节流的函数。
|
|
106
|
+
* @param wait - 等待时间(毫秒)或包含 `wait`、`leading` 和 `trailing` 选项的对象。
|
|
107
|
+
* @returns 返回一个节流函数,该函数具有 `cancel` 方法,用于取消节流操作。
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```typescript
|
|
111
|
+
* const throttledFn = fnThrottle(() => {
|
|
112
|
+
* console.log('Throttled!');
|
|
113
|
+
* }, 100);
|
|
114
|
+
*
|
|
115
|
+
* throttledFn(); // 立即执行
|
|
116
|
+
* throttledFn(); // 忽略
|
|
117
|
+
* throttledFn.cancel(); // 取消节流操作
|
|
118
|
+
* ```
|
|
119
|
+
*/
|
|
120
|
+
export function fnThrottle<F extends AnyFunction>(fn: F, wait: number | TThrottleOptions) {
|
|
121
|
+
const options = isNumber(wait) ? { wait } : wait;
|
|
122
|
+
const waitFinal = options.wait;
|
|
123
|
+
let lastTime = 0;
|
|
124
|
+
let canceled = false;
|
|
125
|
+
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
|
126
|
+
let timer: any;
|
|
127
|
+
|
|
128
|
+
const throttled = function (this: unknown, ...args: Parameters<F>) {
|
|
129
|
+
if (canceled) return;
|
|
130
|
+
|
|
131
|
+
const now = Date.now();
|
|
132
|
+
|
|
133
|
+
// 第一次执行
|
|
134
|
+
if (options.leading && lastTime === 0) {
|
|
135
|
+
lastTime = now;
|
|
136
|
+
fn.apply(this, args);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// 中间控频执行
|
|
140
|
+
else if (lastTime > 0 && now - lastTime >= waitFinal) {
|
|
141
|
+
lastTime = now;
|
|
142
|
+
fn.apply(this, args);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// 首次计时
|
|
146
|
+
else if (lastTime === 0) {
|
|
147
|
+
lastTime = now;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// 最后一次执行
|
|
151
|
+
if (options.trailing) {
|
|
152
|
+
clearTimeout(timer);
|
|
153
|
+
timer = setTimeout(() => {
|
|
154
|
+
fn.apply(this, args);
|
|
155
|
+
}, waitFinal);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
throttled.cancel = () => {
|
|
160
|
+
canceled = true;
|
|
161
|
+
clearTimeout(timer);
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
return throttled;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 创建一个只执行一次的函数,无论调用多少次,实际执行的函数体也只会执行一次。
|
|
169
|
+
*
|
|
170
|
+
* @param fn - 需要只执行一次的函数。
|
|
171
|
+
* @returns 返回一个只执行一次的函数,该函数在第一次调用后会缓存结果并返回缓存的结果。
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* ```typescript
|
|
175
|
+
* const onceFn = fnOnce(() => {
|
|
176
|
+
* console.log('This will be logged only once.');
|
|
177
|
+
* return 42;
|
|
178
|
+
* });
|
|
179
|
+
*
|
|
180
|
+
* console.log(onceFn()); // 输出: This will be logged only once. 42
|
|
181
|
+
* console.log(onceFn()); // 输出: 42
|
|
182
|
+
* ```
|
|
183
|
+
*/
|
|
184
|
+
export function fnOnce<F extends AnyFunction>(fn: F) {
|
|
185
|
+
let called = false;
|
|
186
|
+
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
|
187
|
+
let result: any;
|
|
188
|
+
|
|
189
|
+
return function (this: unknown, ...args: Parameters<F>) {
|
|
190
|
+
if (!called) {
|
|
191
|
+
called = true;
|
|
192
|
+
result = fn.apply(this, args);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return result;
|
|
196
|
+
};
|
|
197
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const VERSION = PKG_VERSION;
|