@nickyzj2023/utils 1.0.15 → 1.0.17

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/src/lru-cache.ts CHANGED
@@ -1,50 +1,50 @@
1
- /**
2
- * 简易 LRU 缓存
3
- * @example
4
- * const cache = new LRUCache<string, number>(2);
5
- * cache.set("a", 1);
6
- * cache.set("b", 2);
7
- * cache.set("c", 3); // 缓存已满,a 被淘汰
8
- * cache.get("a"); // undefined
9
- */
10
- class LRUCache<K, V> {
11
- private cache: Map<K, V>;
12
- private maxSize: number;
13
-
14
- constructor(maxSize = 10) {
15
- this.cache = new Map();
16
- this.maxSize = maxSize;
17
- }
18
-
19
- get(key: K): V | undefined {
20
- const value = this.cache.get(key);
21
- if (!value) {
22
- return undefined;
23
- }
24
- // 重置缓存顺序
25
- this.cache.delete(key);
26
- this.cache.set(key, value);
27
- return value;
28
- }
29
-
30
- set(key: K, value: V) {
31
- // 刷新缓存
32
- if (this.cache.has(key)) {
33
- this.cache.delete(key);
34
- }
35
- // 删除最旧的缓存
36
- else if (this.cache.size >= this.maxSize) {
37
- const oldestKey = [...this.cache.keys()][0];
38
- if (oldestKey) {
39
- this.cache.delete(oldestKey);
40
- }
41
- }
42
- this.cache.set(key, value);
43
- }
44
-
45
- has(key: K) {
46
- return this.cache.has(key);
47
- }
48
- }
49
-
50
- export default LRUCache;
1
+ /**
2
+ * 简易 LRU 缓存
3
+ * @example
4
+ * const cache = new LRUCache<string, number>(2);
5
+ * cache.set("a", 1);
6
+ * cache.set("b", 2);
7
+ * cache.set("c", 3); // 缓存已满,a 被淘汰
8
+ * cache.get("a"); // undefined
9
+ */
10
+ class LRUCache<K, V> {
11
+ private cache: Map<K, V>;
12
+ private maxSize: number;
13
+
14
+ constructor(maxSize = 10) {
15
+ this.cache = new Map();
16
+ this.maxSize = maxSize;
17
+ }
18
+
19
+ get(key: K): V | undefined {
20
+ const value = this.cache.get(key);
21
+ if (!value) {
22
+ return undefined;
23
+ }
24
+ // 重置缓存顺序
25
+ this.cache.delete(key);
26
+ this.cache.set(key, value);
27
+ return value;
28
+ }
29
+
30
+ set(key: K, value: V) {
31
+ // 刷新缓存
32
+ if (this.cache.has(key)) {
33
+ this.cache.delete(key);
34
+ }
35
+ // 删除最旧的缓存
36
+ else if (this.cache.size >= this.maxSize) {
37
+ const oldestKey = [...this.cache.keys()][0];
38
+ if (oldestKey) {
39
+ this.cache.delete(oldestKey);
40
+ }
41
+ }
42
+ this.cache.set(key, value);
43
+ }
44
+
45
+ has(key: K) {
46
+ return this.cache.has(key);
47
+ }
48
+ }
49
+
50
+ export default LRUCache;
package/src/network.ts CHANGED
@@ -1,111 +1,111 @@
1
- import { isObject } from "./is";
2
- import { mergeObjects } from "./object";
3
-
4
- type RequestInit = BunFetchRequestInit & {
5
- parser?: (response: Response) => Promise<any>;
6
- };
7
-
8
- /**
9
- * 基于 Fetch API 的请求客户端
10
- * @param baseURL 接口前缀,如 https://nickyzj.run:3030,也可以不填
11
- * @param defaultOptions 客户端级别的请求选项,方法级别的选项会覆盖这里的相同值
12
- *
13
- * @remarks
14
- * 特性:
15
- * - 合并客户端级别、方法级别的请求选项
16
- * - 在 body 里直接传递对象
17
- * - 可选择使用 to() 处理返回结果为 [Error, Response]
18
- * - 可选择使用 withCache() 缓存请求结果
19
- *
20
- * @example
21
- * // 用法1:创建客户端
22
- * const api = fetcher("https://nickyzj.run:3030", { headers: { Authorization: "Bearer token" } });
23
- * const res = await api.get<Blog>("/blogs/hello-world");
24
- *
25
- * // 用法2:直接发送请求
26
- * const res = await fetcher().get<Blog>("https://nickyzj.run:3030/blogs/hello-world");
27
- *
28
- * // 安全处理返回结果
29
- * const [error, data] = await to(api.get<Blog>("/blogs/hello-world"));
30
- * if (error) {
31
- * console.error(error);
32
- * return;
33
- * }
34
- *
35
- * // 缓存请求结果
36
- * const getBlogs = withCache(api.get);
37
- * await getBlogs("/blogs");
38
- * await sleep(1000);
39
- * await getBlogs("/blogs"); // 不请求,使用缓存结果
40
- */
41
- export const fetcher = (baseURL = "", defaultOptions: RequestInit = {}) => {
42
- const createRequest = async <T>(
43
- path: string,
44
- requestOptions: RequestInit = {},
45
- ) => {
46
- // 构建完整 URL
47
- const url = baseURL ? `${baseURL}${path}` : path;
48
-
49
- // 合并 options
50
- const { parser, ...options } = mergeObjects(defaultOptions, requestOptions);
51
-
52
- // 转换 body 为字符串
53
- if (isObject(options.body)) {
54
- options.body = JSON.stringify(options.body);
55
- options.headers = {
56
- ...options.headers,
57
- "Content-Type": "application/json",
58
- };
59
- }
60
-
61
- // 发送请求
62
- const response = await fetch(url, options);
63
- if (!response.ok) {
64
- throw new Error(response.statusText);
65
- }
66
-
67
- const data = await (parser?.(response) ?? response.json());
68
- return data as T;
69
- };
70
-
71
- return {
72
- get: <T>(url: string, options: Omit<RequestInit, "method"> = {}) =>
73
- createRequest<T>(url, { ...options, method: "GET" }),
74
-
75
- post: <T>(
76
- url: string,
77
- body: any,
78
- options: Omit<RequestInit, "method" | "body"> = {},
79
- ) => createRequest<T>(url, { ...options, method: "POST", body }),
80
-
81
- put: <T>(
82
- url: string,
83
- body: any,
84
- options: Omit<RequestInit, "method" | "body"> = {},
85
- ) => createRequest<T>(url, { ...options, method: "PUT", body }),
86
-
87
- delete: <T>(
88
- url: string,
89
- options: Omit<RequestInit, "method" | "body"> = {},
90
- ) => createRequest<T>(url, { ...options, method: "DELETE" }),
91
- };
92
- };
93
-
94
- /**
95
- * Go 语言风格的异步处理方式
96
- * @param promise 一个能被 await 的异步函数
97
- * @returns 如果成功,返回 [null, 异步函数结果],否则返回 [Error, undefined]
98
- *
99
- * @example
100
- * const [error, response] = await to(fetcher().get<Blog>("/blogs/hello-world"));
101
- */
102
- export const to = async <T, U = Error>(
103
- promise: Promise<T>,
104
- ): Promise<[null, T] | [U, undefined]> => {
105
- try {
106
- const response = await promise;
107
- return [null, response];
108
- } catch (error) {
109
- return [error as U, undefined];
110
- }
111
- };
1
+ import { isObject } from "./is";
2
+ import { mergeObjects } from "./object";
3
+
4
+ export type RequestInit = BunFetchRequestInit & {
5
+ parser?: (response: Response) => Promise<any>;
6
+ };
7
+
8
+ /**
9
+ * 基于 Fetch API 的请求客户端
10
+ * @param baseURL 接口前缀,如 https://nickyzj.run:3030,也可以不填
11
+ * @param defaultOptions 客户端级别的请求选项,方法级别的选项会覆盖这里的相同值
12
+ *
13
+ * @remarks
14
+ * 特性:
15
+ * - 合并客户端级别、方法级别的请求选项
16
+ * - 在 body 里直接传递对象
17
+ * - 可选择使用 to() 处理返回结果为 [Error, Response]
18
+ * - 可选择使用 withCache() 缓存请求结果
19
+ *
20
+ * @example
21
+ * // 用法1:创建客户端
22
+ * const api = fetcher("https://nickyzj.run:3030", { headers: { Authorization: "Bearer token" } });
23
+ * const res = await api.get<Blog>("/blogs/hello-world");
24
+ *
25
+ * // 用法2:直接发送请求
26
+ * const res = await fetcher().get<Blog>("https://nickyzj.run:3030/blogs/hello-world");
27
+ *
28
+ * // 安全处理返回结果
29
+ * const [error, data] = await to(api.get<Blog>("/blogs/hello-world"));
30
+ * if (error) {
31
+ * console.error(error);
32
+ * return;
33
+ * }
34
+ *
35
+ * // 缓存请求结果
36
+ * const getBlogs = withCache(api.get);
37
+ * await getBlogs("/blogs");
38
+ * await sleep(1000);
39
+ * await getBlogs("/blogs"); // 不请求,使用缓存结果
40
+ */
41
+ export const fetcher = (baseURL = "", defaultOptions: RequestInit = {}) => {
42
+ const createRequest = async <T>(
43
+ path: string,
44
+ requestOptions: RequestInit = {},
45
+ ) => {
46
+ // 构建完整 URL
47
+ const url = baseURL ? `${baseURL}${path}` : path;
48
+
49
+ // 合并 options
50
+ const { parser, ...options } = mergeObjects(defaultOptions, requestOptions);
51
+
52
+ // 转换 body 为字符串
53
+ if (isObject(options.body)) {
54
+ options.body = JSON.stringify(options.body);
55
+ options.headers = {
56
+ ...options.headers,
57
+ "Content-Type": "application/json",
58
+ };
59
+ }
60
+
61
+ // 发送请求
62
+ const response = await fetch(url, options);
63
+ if (!response.ok) {
64
+ throw new Error(response.statusText);
65
+ }
66
+
67
+ const data = await (parser?.(response) ?? response.json());
68
+ return data as T;
69
+ };
70
+
71
+ return {
72
+ get: <T>(url: string, options: Omit<RequestInit, "method"> = {}) =>
73
+ createRequest<T>(url, { ...options, method: "GET" }),
74
+
75
+ post: <T>(
76
+ url: string,
77
+ body: any,
78
+ options: Omit<RequestInit, "method" | "body"> = {},
79
+ ) => createRequest<T>(url, { ...options, method: "POST", body }),
80
+
81
+ put: <T>(
82
+ url: string,
83
+ body: any,
84
+ options: Omit<RequestInit, "method" | "body"> = {},
85
+ ) => createRequest<T>(url, { ...options, method: "PUT", body }),
86
+
87
+ delete: <T>(
88
+ url: string,
89
+ options: Omit<RequestInit, "method" | "body"> = {},
90
+ ) => createRequest<T>(url, { ...options, method: "DELETE" }),
91
+ };
92
+ };
93
+
94
+ /**
95
+ * Go 语言风格的异步处理方式
96
+ * @param promise 一个能被 await 的异步函数
97
+ * @returns 如果成功,返回 [null, 异步函数结果],否则返回 [Error, undefined]
98
+ *
99
+ * @example
100
+ * const [error, response] = await to(fetcher().get<Blog>("/blogs/hello-world"));
101
+ */
102
+ export const to = async <T, U = Error>(
103
+ promise: Promise<T>,
104
+ ): Promise<[null, T] | [U, undefined]> => {
105
+ try {
106
+ const response = await promise;
107
+ return [null, response];
108
+ } catch (error) {
109
+ return [error as U, undefined];
110
+ }
111
+ };
package/src/object.ts CHANGED
@@ -1,52 +1,52 @@
1
- import { isObject, isPrimitive } from "./is";
2
-
3
- /**
4
- * 深度合并两个对象,规则如下:
5
- * 1. 原始值覆盖:如果两个值都是原始类型(string、number、boolean、null、undefined、symbol、bigint),则用后者覆盖;
6
- * 2. 数组拼接:如果两个值都是数组,则拼接为大数组;
7
- * 3. 对象递归合并:如果两个值都是对象,则进行递归深度合并;
8
- * 4. 类型不匹配覆盖:如果两个值的类型不同,则用后者覆盖;
9
- * 5. 独有属性保留:如果字段只存在于其中一个对象中,则保留它。
10
- *
11
- * @template T 第一个对象
12
- * @template U 第二个对象
13
- * @param {T} obj1 要合并的第一个对象,相同字段可能会被 obj2 覆盖
14
- * @param {U} obj2 要合并的第二个对象
15
- */
16
- export const mergeObjects = <
17
- T extends Record<string, any>,
18
- U extends Record<string, any>,
19
- >(
20
- obj1: T,
21
- obj2: U,
22
- ) => {
23
- const result: Record<string, any> = { ...obj1 };
24
-
25
- for (const key of Object.keys(obj2)) {
26
- const val1 = result[key];
27
- const val2 = obj2[key];
28
-
29
- // 如果都是原始值,则用后者覆盖
30
- if (isPrimitive(val1) && isPrimitive(val2)) {
31
- result[key] = val2;
32
- continue;
33
- }
34
-
35
- // 如果都是数组,则拼接为大数组
36
- if (Array.isArray(val1) && Array.isArray(val2)) {
37
- result[key] = val1.concat(val2);
38
- continue;
39
- }
40
-
41
- // 如果都是对象,则深度递归合并
42
- if (isObject(val1) && isObject(val2)) {
43
- result[key] = mergeObjects(val1, val2);
44
- continue;
45
- }
46
-
47
- // 如果类型不同,则用后者覆盖
48
- result[key] = val2;
49
- }
50
-
51
- return result as T & U;
52
- };
1
+ import { isObject, isPrimitive } from "./is";
2
+
3
+ /**
4
+ * 深度合并两个对象,规则如下:
5
+ * 1. 原始值覆盖:如果两个值都是原始类型(string、number、boolean、null、undefined、symbol、bigint),则用后者覆盖;
6
+ * 2. 数组拼接:如果两个值都是数组,则拼接为大数组;
7
+ * 3. 对象递归合并:如果两个值都是对象,则进行递归深度合并;
8
+ * 4. 类型不匹配覆盖:如果两个值的类型不同,则用后者覆盖;
9
+ * 5. 独有属性保留:如果字段只存在于其中一个对象中,则保留它。
10
+ *
11
+ * @template T 第一个对象
12
+ * @template U 第二个对象
13
+ * @param {T} obj1 要合并的第一个对象,相同字段可能会被 obj2 覆盖
14
+ * @param {U} obj2 要合并的第二个对象
15
+ */
16
+ export const mergeObjects = <
17
+ T extends Record<string, any>,
18
+ U extends Record<string, any>,
19
+ >(
20
+ obj1: T,
21
+ obj2: U,
22
+ ) => {
23
+ const result: Record<string, any> = { ...obj1 };
24
+
25
+ for (const key of Object.keys(obj2)) {
26
+ const val1 = result[key];
27
+ const val2 = obj2[key];
28
+
29
+ // 如果都是原始值,则用后者覆盖
30
+ if (isPrimitive(val1) && isPrimitive(val2)) {
31
+ result[key] = val2;
32
+ continue;
33
+ }
34
+
35
+ // 如果都是数组,则拼接为大数组
36
+ if (Array.isArray(val1) && Array.isArray(val2)) {
37
+ result[key] = val1.concat(val2);
38
+ continue;
39
+ }
40
+
41
+ // 如果都是对象,则深度递归合并
42
+ if (isObject(val1) && isObject(val2)) {
43
+ result[key] = mergeObjects(val1, val2);
44
+ continue;
45
+ }
46
+
47
+ // 如果类型不同,则用后者覆盖
48
+ result[key] = val2;
49
+ }
50
+
51
+ return result as T & U;
52
+ };
package/src/string.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 转换下划线命名法为驼峰命名法
3
+ *
4
+ * @example
5
+ * snakeToCamel("user_name") // 'userName'
6
+ */
7
+ export const snakeToCamel = (str: string) => {
8
+ return str.replace(/_([a-zA-Z])/g, (match, pattern) => pattern.toUpperCase());
9
+ };
10
+
11
+ /**
12
+ * 转换驼峰命名法为下划线命名法
13
+ *
14
+ * @example
15
+ * camelToSnake("shouldComponentUpdate") // 'should_component_update'
16
+ */
17
+ export const camelToSnake = (str: string) => {
18
+ return str.replace(
19
+ /([A-Z])/g,
20
+ (match, pattern) => `_${pattern.toLowerCase()}`,
21
+ );
22
+ };
package/src/time.ts CHANGED
@@ -1,11 +1,11 @@
1
- /**
2
- * 延迟一段时间再执行后续代码
3
- * @param time 延迟时间,默认 150ms
4
- * @example
5
- * await sleep(1000); // 等待 1 秒执行后续代码
6
- */
7
- export const sleep = async (time = 150) => {
8
- return new Promise((resolve) => {
9
- setTimeout(resolve, time);
10
- });
11
- };
1
+ /**
2
+ * 延迟一段时间再执行后续代码
3
+ * @param time 延迟时间,默认 150ms
4
+ * @example
5
+ * await sleep(1000); // 等待 1 秒执行后续代码
6
+ */
7
+ export const sleep = async (time = 150) => {
8
+ return new Promise((resolve) => {
9
+ setTimeout(resolve, time);
10
+ });
11
+ };
package/tsconfig.json CHANGED
@@ -1,32 +1,32 @@
1
- {
2
- "compilerOptions": {
3
- // Environment setup & latest features
4
- "lib": ["ESNext", "DOM"],
5
- "target": "ESNext",
6
- "module": "Preserve",
7
- "moduleDetection": "force",
8
- "jsx": "react-jsx",
9
- "allowJs": true,
10
-
11
- // Bundler mode
12
- "moduleResolution": "bundler",
13
- "allowImportingTsExtensions": true,
14
- "verbatimModuleSyntax": true,
15
- "outDir": "dist",
16
- "declaration": true,
17
- "emitDeclarationOnly": true,
18
-
19
- // Best practices
20
- "strict": true,
21
- "skipLibCheck": true,
22
- "noFallthroughCasesInSwitch": true,
23
- "noUncheckedIndexedAccess": true,
24
- "noImplicitOverride": true,
25
-
26
- // Some stricter flags (disabled by default)
27
- "noUnusedLocals": false,
28
- "noUnusedParameters": false,
29
- "noPropertyAccessFromIndexSignature": false
30
- },
31
- "include": ["src"]
32
- }
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup & latest features
4
+ "lib": ["ESNext", "DOM"],
5
+ "target": "ESNext",
6
+ "module": "Preserve",
7
+ "moduleDetection": "force",
8
+ "jsx": "react-jsx",
9
+ "allowJs": true,
10
+
11
+ // Bundler mode
12
+ "moduleResolution": "bundler",
13
+ "allowImportingTsExtensions": true,
14
+ "verbatimModuleSyntax": true,
15
+ "outDir": "dist",
16
+ "declaration": true,
17
+ "emitDeclarationOnly": true,
18
+
19
+ // Best practices
20
+ "strict": true,
21
+ "skipLibCheck": true,
22
+ "noFallthroughCasesInSwitch": true,
23
+ "noUncheckedIndexedAccess": true,
24
+ "noImplicitOverride": true,
25
+
26
+ // Some stricter flags (disabled by default)
27
+ "noUnusedLocals": false,
28
+ "noUnusedParameters": false,
29
+ "noPropertyAccessFromIndexSignature": false
30
+ },
31
+ "include": ["src"]
32
+ }