a2bei4-utils 1.0.0
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/LICENSE +21 -0
- package/README.md +2 -0
- package/dist/a2bei4.utils.cjs.js +1112 -0
- package/dist/a2bei4.utils.cjs.js.map +1 -0
- package/dist/a2bei4.utils.cjs.min.js +2 -0
- package/dist/a2bei4.utils.cjs.min.js.map +1 -0
- package/dist/a2bei4.utils.esm.js +1070 -0
- package/dist/a2bei4.utils.esm.js.map +1 -0
- package/dist/a2bei4.utils.esm.min.js +2 -0
- package/dist/a2bei4.utils.esm.min.js.map +1 -0
- package/dist/a2bei4.utils.umd.js +1118 -0
- package/dist/a2bei4.utils.umd.js.map +1 -0
- package/dist/a2bei4.utils.umd.min.js +2 -0
- package/dist/a2bei4.utils.umd.min.js.map +1 -0
- package/dist/arr.cjs +34 -0
- package/dist/arr.cjs.map +1 -0
- package/dist/arr.js +31 -0
- package/dist/arr.js.map +1 -0
- package/dist/browser.cjs +60 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.js +56 -0
- package/dist/browser.js.map +1 -0
- package/dist/common.cjs +391 -0
- package/dist/common.cjs.map +1 -0
- package/dist/common.js +373 -0
- package/dist/common.js.map +1 -0
- package/dist/date.cjs +195 -0
- package/dist/date.cjs.map +1 -0
- package/dist/date.js +188 -0
- package/dist/date.js.map +1 -0
- package/dist/download.cjs +70 -0
- package/dist/download.cjs.map +1 -0
- package/dist/download.js +64 -0
- package/dist/download.js.map +1 -0
- package/dist/evt.cjs +155 -0
- package/dist/evt.cjs.map +1 -0
- package/dist/evt.js +152 -0
- package/dist/evt.js.map +1 -0
- package/dist/id.cjs +75 -0
- package/dist/id.cjs.map +1 -0
- package/dist/id.js +72 -0
- package/dist/id.js.map +1 -0
- package/dist/timer.cjs +57 -0
- package/dist/timer.cjs.map +1 -0
- package/dist/timer.js +55 -0
- package/dist/timer.js.map +1 -0
- package/dist/tree.cjs +99 -0
- package/dist/tree.cjs.map +1 -0
- package/dist/tree.js +95 -0
- package/dist/tree.js.map +1 -0
- package/package.json +146 -0
- package/readme.txt +18 -0
- package/types/arr.d.ts +18 -0
- package/types/browser.d.ts +51 -0
- package/types/common.d.ts +170 -0
- package/types/date.d.ts +77 -0
- package/types/download.d.ts +39 -0
- package/types/evt.d.ts +52 -0
- package/types/id.d.ts +39 -0
- package/types/index.d.ts +499 -0
- package/types/timer.d.ts +32 -0
- package/types/tree.d.ts +30 -0
package/dist/tree.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 把嵌套树拍平成 `{ [id]: node }` 映射,同时把原 `children` 置为 `null`。
|
|
3
|
+
*
|
|
4
|
+
* @template T extends Record<PropertyKey, any>
|
|
5
|
+
* @param {T[]} data - 嵌套树森林
|
|
6
|
+
* @param {string} [idKey='id'] - 主键字段
|
|
7
|
+
* @param {string} [childrenKey='children'] - 子节点字段
|
|
8
|
+
* @returns {Record<string, T & { [k in typeof childrenKey]: null }>} id→节点的映射表
|
|
9
|
+
*/
|
|
10
|
+
function nestedTree2IdMap(data, idKey = "id", childrenKey = "children") {
|
|
11
|
+
const retObj = {};
|
|
12
|
+
function fn(nodes) {
|
|
13
|
+
if (Array.isArray(nodes) && nodes.length > 0) {
|
|
14
|
+
nodes.forEach((node) => {
|
|
15
|
+
retObj[node[idKey]] = { ...node };
|
|
16
|
+
retObj[node[idKey]][childrenKey] = null;
|
|
17
|
+
|
|
18
|
+
fn(node[childrenKey]);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
fn(data);
|
|
23
|
+
return retObj;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 把**已包含完整父子关系**的扁平节点列表还原成嵌套树(森林)。
|
|
28
|
+
*
|
|
29
|
+
* @template T extends Record<PropertyKey, any>
|
|
30
|
+
* @param {T[]} nodes - 扁平节点列表(必须包含 id / parentId)
|
|
31
|
+
* @param {number | string} [parentId=0] - 根节点标识值
|
|
32
|
+
* @param {Object} [opts] - 字段映射配置
|
|
33
|
+
* @param {string} [opts.idKey='id'] - 节点主键
|
|
34
|
+
* @param {string} [opts.parentKey='parentId'] - 父节点外键
|
|
35
|
+
* @param {string} [opts.childrenKey='children'] - 存放子节点的字段
|
|
36
|
+
* @returns {(T & { [k in typeof childrenKey]: T[] })[]} 嵌套树森林
|
|
37
|
+
*/
|
|
38
|
+
function flatCompleteTree2NestedTree(nodes, parentId = 0, { idKey = "id", parentKey = "parentId", childrenKey = "children" } = {}) {
|
|
39
|
+
const map = new Map(); // id -> node
|
|
40
|
+
const items = []; // 多根森林
|
|
41
|
+
|
|
42
|
+
// 1. 初始化:保证每个节点都有 children,并存入 map
|
|
43
|
+
for (const item of nodes) {
|
|
44
|
+
const node = { ...item, [childrenKey]: [] };
|
|
45
|
+
map.set(item[idKey], node);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 2. 建立父子关系
|
|
49
|
+
for (const item of nodes) {
|
|
50
|
+
const node = map.get(item[idKey]);
|
|
51
|
+
const parentIdVal = item[parentKey];
|
|
52
|
+
|
|
53
|
+
if (parentIdVal === parentId) {
|
|
54
|
+
// 根层
|
|
55
|
+
items.push(node);
|
|
56
|
+
} else {
|
|
57
|
+
// 非根层:找到父节点,把自己挂上去
|
|
58
|
+
const parent = map.get(parentIdVal);
|
|
59
|
+
if (parent) parent[childrenKey].push(node);
|
|
60
|
+
// 如果 parent 不存在,说明数据不完整,可自定义处理
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return items;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 在嵌套树中按 `id` 递归查找节点,并返回其指定属性值。
|
|
69
|
+
*
|
|
70
|
+
* @template T extends Record<PropertyKey, any>
|
|
71
|
+
* @param {string | number} id - 要查找的 id
|
|
72
|
+
* @param {T[]} arr - 嵌套树森林
|
|
73
|
+
* @param {string} [resultKey='name'] - 需要返回的字段
|
|
74
|
+
* @param {string} [idKey='id'] - 主键字段
|
|
75
|
+
* @param {string} [childrenKey='children'] - 子节点字段
|
|
76
|
+
* @returns {any} 找到的值;未找到返回 `undefined`
|
|
77
|
+
*/
|
|
78
|
+
const findObjAttrValueById = function findObjAttrValueByIdFn(id, arr, resultKey = "name", idKey = "id", childrenKey = "children") {
|
|
79
|
+
if (Array.isArray(arr) && arr.length > 0) {
|
|
80
|
+
for (let i = 0; i < arr.length; i++) {
|
|
81
|
+
const item = arr[i];
|
|
82
|
+
if (item[idKey]?.toString() === id?.toString()) {
|
|
83
|
+
return item[resultKey];
|
|
84
|
+
} else if (Array.isArray(item[childrenKey]) && item[childrenKey].length > 0) {
|
|
85
|
+
const result = findObjAttrValueByIdFn(id, item[childrenKey], resultKey, idKey, childrenKey);
|
|
86
|
+
if (result) {
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
export { findObjAttrValueById, flatCompleteTree2NestedTree, nestedTree2IdMap };
|
|
95
|
+
//# sourceMappingURL=tree.js.map
|
package/dist/tree.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tree.js","sources":["../src/source/tree.js"],"sourcesContent":["/**\n * 把嵌套树拍平成 `{ [id]: node }` 映射,同时把原 `children` 置为 `null`。\n *\n * @template T extends Record<PropertyKey, any>\n * @param {T[]} data - 嵌套树森林\n * @param {string} [idKey='id'] - 主键字段\n * @param {string} [childrenKey='children'] - 子节点字段\n * @returns {Record<string, T & { [k in typeof childrenKey]: null }>} id→节点的映射表\n */\nexport function nestedTree2IdMap(data, idKey = \"id\", childrenKey = \"children\") {\n const retObj = {};\n function fn(nodes) {\n if (Array.isArray(nodes) && nodes.length > 0) {\n nodes.forEach((node) => {\n retObj[node[idKey]] = { ...node };\n retObj[node[idKey]][childrenKey] = null;\n\n fn(node[childrenKey]);\n });\n }\n }\n fn(data);\n return retObj;\n}\n\n/**\n * 把**已包含完整父子关系**的扁平节点列表还原成嵌套树(森林)。\n *\n * @template T extends Record<PropertyKey, any>\n * @param {T[]} nodes - 扁平节点列表(必须包含 id / parentId)\n * @param {number | string} [parentId=0] - 根节点标识值\n * @param {Object} [opts] - 字段映射配置\n * @param {string} [opts.idKey='id'] - 节点主键\n * @param {string} [opts.parentKey='parentId'] - 父节点外键\n * @param {string} [opts.childrenKey='children'] - 存放子节点的字段\n * @returns {(T & { [k in typeof childrenKey]: T[] })[]} 嵌套树森林\n */\nexport function flatCompleteTree2NestedTree(nodes, parentId = 0, { idKey = \"id\", parentKey = \"parentId\", childrenKey = \"children\" } = {}) {\n const map = new Map(); // id -> node\n const items = []; // 多根森林\n\n // 1. 初始化:保证每个节点都有 children,并存入 map\n for (const item of nodes) {\n const node = { ...item, [childrenKey]: [] };\n map.set(item[idKey], node);\n }\n\n // 2. 建立父子关系\n for (const item of nodes) {\n const node = map.get(item[idKey]);\n const parentIdVal = item[parentKey];\n\n if (parentIdVal === parentId) {\n // 根层\n items.push(node);\n } else {\n // 非根层:找到父节点,把自己挂上去\n const parent = map.get(parentIdVal);\n if (parent) parent[childrenKey].push(node);\n // 如果 parent 不存在,说明数据不完整,可自定义处理\n }\n }\n\n return items;\n}\n\n/**\n * 在嵌套树中按 `id` 递归查找节点,并返回其指定属性值。\n *\n * @template T extends Record<PropertyKey, any>\n * @param {string | number} id - 要查找的 id\n * @param {T[]} arr - 嵌套树森林\n * @param {string} [resultKey='name'] - 需要返回的字段\n * @param {string} [idKey='id'] - 主键字段\n * @param {string} [childrenKey='children'] - 子节点字段\n * @returns {any} 找到的值;未找到返回 `undefined`\n */\nexport const findObjAttrValueById = function findObjAttrValueByIdFn(id, arr, resultKey = \"name\", idKey = \"id\", childrenKey = \"children\") {\n if (Array.isArray(arr) && arr.length > 0) {\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n if (item[idKey]?.toString() === id?.toString()) {\n return item[resultKey];\n } else if (Array.isArray(item[childrenKey]) && item[childrenKey].length > 0) {\n const result = findObjAttrValueByIdFn(id, item[childrenKey], resultKey, idKey, childrenKey);\n if (result) {\n return result;\n }\n }\n }\n }\n};\n"],"names":[],"mappings":"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"}
|
package/package.json
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "a2bei4-utils",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "🧰 零依赖、ESM 的 JS 业务工具箱:数组乱序/深浅克隆、防抖节流、URL/query 解析、Date/时长格式化、随机汉字/字母、文件下载、事件总线、UUID/分布式短 ID、树结构互转等 40+ 常用函数 & 类,Tree-Shaking 友好。",
|
|
5
|
+
"private": false,
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/a2bei4.utils.cjs.js",
|
|
8
|
+
"module": "dist/a2bei4.utils.esm.js",
|
|
9
|
+
"unpkg": "dist/a2bei4.utils.umd.min.js",
|
|
10
|
+
"jsdelivr": "dist/a2bei4.utils.umd.min.js",
|
|
11
|
+
"types": "types/index.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./types/index.d.ts",
|
|
15
|
+
"import": "./dist/a2bei4.utils.esm.js",
|
|
16
|
+
"require": "./dist/a2bei4.utils.cjs.js"
|
|
17
|
+
},
|
|
18
|
+
"./arr": {
|
|
19
|
+
"types": "./types/arr.d.ts",
|
|
20
|
+
"import": "./dist/arr.js",
|
|
21
|
+
"require": "./dist/arr.cjs"
|
|
22
|
+
},
|
|
23
|
+
"./browser": {
|
|
24
|
+
"types": "./types/browser.d.ts",
|
|
25
|
+
"import": "./dist/browser.js",
|
|
26
|
+
"require": "./dist/browser.cjs"
|
|
27
|
+
},
|
|
28
|
+
"./common": {
|
|
29
|
+
"types": "./types/common.d.ts",
|
|
30
|
+
"import": "./dist/common.js",
|
|
31
|
+
"require": "./dist/common.cjs"
|
|
32
|
+
},
|
|
33
|
+
"./date": {
|
|
34
|
+
"types": "./types/date.d.ts",
|
|
35
|
+
"import": "./dist/date.js",
|
|
36
|
+
"require": "./dist/date.cjs"
|
|
37
|
+
},
|
|
38
|
+
"./download": {
|
|
39
|
+
"types": "./types/download.d.ts",
|
|
40
|
+
"import": "./dist/download.js",
|
|
41
|
+
"require": "./dist/download.cjs"
|
|
42
|
+
},
|
|
43
|
+
"./evt": {
|
|
44
|
+
"types": "./types/evt.d.ts",
|
|
45
|
+
"import": "./dist/evt.js",
|
|
46
|
+
"require": "./dist/evt.cjs"
|
|
47
|
+
},
|
|
48
|
+
"./id": {
|
|
49
|
+
"types": "./types/id.d.ts",
|
|
50
|
+
"import": "./dist/id.js",
|
|
51
|
+
"require": "./dist/id.cjs"
|
|
52
|
+
},
|
|
53
|
+
"./timer": {
|
|
54
|
+
"types": "./types/timer.d.ts",
|
|
55
|
+
"import": "./dist/timer.js",
|
|
56
|
+
"require": "./dist/timer.cjs"
|
|
57
|
+
},
|
|
58
|
+
"./tree": {
|
|
59
|
+
"types": "./types/tree.d.ts",
|
|
60
|
+
"import": "./dist/tree.js",
|
|
61
|
+
"require": "./dist/tree.cjs"
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
"files": [
|
|
65
|
+
"dist",
|
|
66
|
+
"types"
|
|
67
|
+
],
|
|
68
|
+
"sideEffects": false,
|
|
69
|
+
"keywords": [
|
|
70
|
+
"a2bei4",
|
|
71
|
+
"xiaodu114",
|
|
72
|
+
"utils",
|
|
73
|
+
"utilities",
|
|
74
|
+
"toolkit",
|
|
75
|
+
"zero-dependency",
|
|
76
|
+
"esm",
|
|
77
|
+
"shuffle",
|
|
78
|
+
"move-array-item",
|
|
79
|
+
"deep-clone",
|
|
80
|
+
"assign-existing",
|
|
81
|
+
"tree-flat",
|
|
82
|
+
"tree-nested",
|
|
83
|
+
"tree-utils",
|
|
84
|
+
"debounce",
|
|
85
|
+
"throttle",
|
|
86
|
+
"random",
|
|
87
|
+
"random-han",
|
|
88
|
+
"random-en",
|
|
89
|
+
"uuid",
|
|
90
|
+
"guid",
|
|
91
|
+
"id",
|
|
92
|
+
"short-id",
|
|
93
|
+
"nanoid",
|
|
94
|
+
"date-format",
|
|
95
|
+
"duration-format",
|
|
96
|
+
"time-diff",
|
|
97
|
+
"random-date",
|
|
98
|
+
"viewport",
|
|
99
|
+
"download",
|
|
100
|
+
"download-excel",
|
|
101
|
+
"download-json",
|
|
102
|
+
"event-bus",
|
|
103
|
+
"cross-page",
|
|
104
|
+
"is-plain-object",
|
|
105
|
+
"is-promise",
|
|
106
|
+
"is-blob",
|
|
107
|
+
"is-date",
|
|
108
|
+
"is-function",
|
|
109
|
+
"get-type",
|
|
110
|
+
"blob-to-text",
|
|
111
|
+
"read-file",
|
|
112
|
+
"file-download",
|
|
113
|
+
"business-utils",
|
|
114
|
+
"frontend-utils",
|
|
115
|
+
"daily-helper"
|
|
116
|
+
],
|
|
117
|
+
"license": "MIT",
|
|
118
|
+
"author": "xiaodu114",
|
|
119
|
+
"publishConfig": {
|
|
120
|
+
"access": "public"
|
|
121
|
+
},
|
|
122
|
+
"repository": {
|
|
123
|
+
"type": "git",
|
|
124
|
+
"url": "git+https://github.com/xiaodu114/a2bei4-utils.git"
|
|
125
|
+
},
|
|
126
|
+
"homepage": "https://github.com/xiaodu114/a2bei4-utils",
|
|
127
|
+
"devDependencies": {
|
|
128
|
+
"@rollup/plugin-commonjs": "^28.0.6",
|
|
129
|
+
"@rollup/plugin-node-resolve": "^16.0.2",
|
|
130
|
+
"@rollup/plugin-terser": "^0.4.4",
|
|
131
|
+
"prettier": "^3.6.2",
|
|
132
|
+
"rollup": "^4.52.4",
|
|
133
|
+
"rollup-plugin-dts": "^6.2.3",
|
|
134
|
+
"rollup-plugin-filesize": "^10.0.0",
|
|
135
|
+
"typescript": "^5.9.3"
|
|
136
|
+
},
|
|
137
|
+
"scripts": {
|
|
138
|
+
"update:package": "node scripts/update-package.js",
|
|
139
|
+
"generate:entry": "node scripts/generate-entry.js",
|
|
140
|
+
"generate:index": "node scripts/generate-index.js",
|
|
141
|
+
"prebuild": "pnpm run update:package && pnpm run generate:entry && pnpm run generate:index",
|
|
142
|
+
"build": "rollup -c",
|
|
143
|
+
"dev": "rollup -c -w",
|
|
144
|
+
"format": "prettier --write \"src/**/*.{js,ts,json,md}\""
|
|
145
|
+
}
|
|
146
|
+
}
|
package/readme.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
0、首次安装依赖
|
|
2
|
+
pnpm i -D @rollup/plugin-commonjs @rollup/plugin-node-resolve @rollup/plugin-terser prettier rollup rollup-plugin-dts rollup-plugin-filesize typescript
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
--> 官方 npm 仓库地址:https://registry.npmjs.org/
|
|
6
|
+
--> --registry 显示指定的仓库地址,如:http://192.168.x.x:4873
|
|
7
|
+
|
|
8
|
+
1、如果没有用户,先注册用户
|
|
9
|
+
pnpm adduser --registry https://registry.npmjs.org/
|
|
10
|
+
|
|
11
|
+
2、用户登录
|
|
12
|
+
pnpm login --registry https://registry.npmjs.org/
|
|
13
|
+
|
|
14
|
+
3、发布
|
|
15
|
+
pnpm publish --registry https://registry.npmjs.org/
|
|
16
|
+
|
|
17
|
+
4、撤销发布
|
|
18
|
+
pnpm unpublish a2bei4-utils --force --registry https://registry.npmjs.org/
|
package/types/arr.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 使用 Fisher-Yates 算法对数组 **原地** 随机乱序。
|
|
3
|
+
* @template T
|
|
4
|
+
* @param {T[]} arr - 要乱序的数组
|
|
5
|
+
* @returns {T[]} 返回传入的同一数组实例(已乱序)
|
|
6
|
+
*/
|
|
7
|
+
declare function shuffle<T>(arr: T[]): T[];
|
|
8
|
+
/**
|
|
9
|
+
* 将数组中的元素从 `fromIndex` 移动到 `toIndex`,**原地** 修改并返回该数组。
|
|
10
|
+
* @template T
|
|
11
|
+
* @param {T[]} arr - 要操作的数组
|
|
12
|
+
* @param {number} fromIndex - 原始下标
|
|
13
|
+
* @param {number} toIndex - 目标下标
|
|
14
|
+
* @returns {T[]} 返回传入的同一数组实例
|
|
15
|
+
*/
|
|
16
|
+
declare function moveItem<T>(arr: T[], fromIndex: number, toIndex: number): T[];
|
|
17
|
+
|
|
18
|
+
export { moveItem, shuffle };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 视口尺寸对象。
|
|
3
|
+
* @typedef {Object} ViewportDimensions
|
|
4
|
+
* @property {number} w 视口宽度,单位像素。
|
|
5
|
+
* @property {number} h 视口高度,单位像素。
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* 获取当前视口(viewport)的宽高。
|
|
9
|
+
*
|
|
10
|
+
* 兼容策略:
|
|
11
|
+
* 1. 优先使用 `window.innerWidth/innerHeight`(现代浏览器)。
|
|
12
|
+
* 2. 降级到 `document.documentElement.clientWidth/clientHeight`(IE9+ 及怪异模式)。
|
|
13
|
+
* 3. 最后降级到 `document.body.clientWidth/clientHeight`(IE6-8 怪异模式)。
|
|
14
|
+
*
|
|
15
|
+
* @returns {ViewportDimensions} 包含 `w`(宽度)和 `h`(高度)的对象,单位为像素。
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* const { w, h } = getViewportSize();
|
|
19
|
+
* console.log(`视口尺寸:${w} × ${h}`);
|
|
20
|
+
*/
|
|
21
|
+
declare function getViewportSize(): ViewportDimensions;
|
|
22
|
+
/**
|
|
23
|
+
* 将当前页面 URL 的 query 部分解析成键值对对象。
|
|
24
|
+
*
|
|
25
|
+
* @returns {Record<string, string>} 所有查询参数组成的平凡对象
|
|
26
|
+
* (同名 key 仅保留最后一项)
|
|
27
|
+
*/
|
|
28
|
+
declare function getAllSearchParams(): Record<string, string>;
|
|
29
|
+
/**
|
|
30
|
+
* 根据 key 获取当前页面 URL 中的单个查询参数。
|
|
31
|
+
*
|
|
32
|
+
* @param {string} key - 要提取的参数名
|
|
33
|
+
* @returns {string | undefined} 对应参数值;不存在时返回 `undefined`
|
|
34
|
+
*/
|
|
35
|
+
declare function getSearchParam(key: string): string | undefined;
|
|
36
|
+
/**
|
|
37
|
+
* 视口尺寸对象。
|
|
38
|
+
*/
|
|
39
|
+
type ViewportDimensions = {
|
|
40
|
+
/**
|
|
41
|
+
* 视口宽度,单位像素。
|
|
42
|
+
*/
|
|
43
|
+
w: number;
|
|
44
|
+
/**
|
|
45
|
+
* 视口高度,单位像素。
|
|
46
|
+
*/
|
|
47
|
+
h: number;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export { getAllSearchParams, getSearchParam, getViewportSize };
|
|
51
|
+
export type { ViewportDimensions };
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 返回任意值的运行时类型字符串(小写形式)。
|
|
3
|
+
*
|
|
4
|
+
* @param {*} obj 待检测的值
|
|
5
|
+
* @returns {keyof globalThis|"blob"|"file"|"formdata"|string} 小写类型名
|
|
6
|
+
*/
|
|
7
|
+
declare function getDataType(obj: any): ("undefined" | "globalThis" | "eval" | "parseInt" | "parseFloat" | "isNaN" | "isFinite" | "decodeURI" | "decodeURIComponent" | "encodeURI" | "encodeURIComponent" | "escape" | "unescape" | "NaN" | "Infinity" | "Symbol" | "Object" | "Function" | "String" | "Boolean" | "Number" | "Math" | "Date" | "RegExp" | "Error" | "EvalError" | "RangeError" | "ReferenceError" | "SyntaxError" | "TypeError" | "URIError" | "JSON" | "Array" | "Promise" | "ArrayBuffer" | "DataView" | "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array" | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array" | "Intl" | "alert" | "blur" | "cancelIdleCallback" | "captureEvents" | "close" | "confirm" | "focus" | "getComputedStyle" | "getSelection" | "matchMedia" | "moveBy" | "moveTo" | "open" | "postMessage" | "print" | "prompt" | "releaseEvents" | "requestIdleCallback" | "resizeBy" | "resizeTo" | "scroll" | "scrollBy" | "scrollTo" | "stop" | "toString" | "dispatchEvent" | "cancelAnimationFrame" | "requestAnimationFrame" | "atob" | "btoa" | "clearInterval" | "clearTimeout" | "createImageBitmap" | "fetch" | "queueMicrotask" | "reportError" | "setInterval" | "setTimeout" | "structuredClone" | "addEventListener" | "removeEventListener" | "NodeFilter" | "AbortController" | "AbortSignal" | "AbstractRange" | "AnalyserNode" | "Animation" | "AnimationEffect" | "AnimationEvent" | "AnimationPlaybackEvent" | "AnimationTimeline" | "Attr" | "AudioBuffer" | "AudioBufferSourceNode" | "AudioContext" | "AudioData" | "AudioDecoder" | "AudioDestinationNode" | "AudioEncoder" | "AudioListener" | "AudioNode" | "AudioParam" | "AudioParamMap" | "AudioProcessingEvent" | "AudioScheduledSourceNode" | "AudioWorklet" | "AudioWorkletNode" | "AuthenticatorAssertionResponse" | "AuthenticatorAttestationResponse" | "AuthenticatorResponse" | "BarProp" | "BaseAudioContext" | "BeforeUnloadEvent" | "BiquadFilterNode" | "Blob" | "BlobEvent" | "BroadcastChannel" | "ByteLengthQueuingStrategy" | "CDATASection" | "CSPViolationReportBody" | "CSSAnimation" | "CSSConditionRule" | "CSSContainerRule" | "CSSCounterStyleRule" | "CSSFontFaceRule" | "CSSFontFeatureValuesRule" | "CSSFontPaletteValuesRule" | "CSSGroupingRule" | "CSSImageValue" | "CSSImportRule" | "CSSKeyframeRule" | "CSSKeyframesRule" | "CSSKeywordValue" | "CSSLayerBlockRule" | "CSSLayerStatementRule" | "CSSMathClamp" | "CSSMathInvert" | "CSSMathMax" | "CSSMathMin" | "CSSMathNegate" | "CSSMathProduct" | "CSSMathSum" | "CSSMathValue" | "CSSMatrixComponent" | "CSSMediaRule" | "CSSNamespaceRule" | "CSSNestedDeclarations" | "CSSNumericArray" | "CSSNumericValue" | "CSSPageRule" | "CSSPerspective" | "CSSPropertyRule" | "CSSRotate" | "CSSRule" | "CSSRuleList" | "CSSScale" | "CSSScopeRule" | "CSSSkew" | "CSSSkewX" | "CSSSkewY" | "CSSStartingStyleRule" | "CSSStyleDeclaration" | "CSSStyleRule" | "CSSStyleSheet" | "CSSStyleValue" | "CSSSupportsRule" | "CSSTransformComponent" | "CSSTransformValue" | "CSSTransition" | "CSSTranslate" | "CSSUnitValue" | "CSSUnparsedValue" | "CSSVariableReferenceValue" | "CSSViewTransitionRule" | "Cache" | "CacheStorage" | "CanvasCaptureMediaStreamTrack" | "CanvasGradient" | "CanvasPattern" | "CanvasRenderingContext2D" | "CaretPosition" | "ChannelMergerNode" | "ChannelSplitterNode" | "CharacterData" | "Clipboard" | "ClipboardEvent" | "ClipboardItem" | "CloseEvent" | "Comment" | "CompositionEvent" | "CompressionStream" | "ConstantSourceNode" | "ContentVisibilityAutoStateChangeEvent" | "ConvolverNode" | "CookieChangeEvent" | "CookieStore" | "CookieStoreManager" | "CountQueuingStrategy" | "Credential" | "CredentialsContainer" | "Crypto" | "CryptoKey" | "CustomElementRegistry" | "CustomEvent" | "CustomStateSet" | "DOMException" | "DOMImplementation" | "DOMMatrix" | "SVGMatrix" | "WebKitCSSMatrix" | "DOMMatrixReadOnly" | "DOMParser" | "DOMPoint" | "SVGPoint" | "DOMPointReadOnly" | "DOMQuad" | "DOMRect" | "SVGRect" | "DOMRectList" | "DOMRectReadOnly" | "DOMStringList" | "DOMStringMap" | "DOMTokenList" | "DataTransfer" | "DataTransferItem" | "DataTransferItemList" | "DecompressionStream" | "DelayNode" | "DeviceMotionEvent" | "DeviceOrientationEvent" | "Document" | "DocumentFragment" | "DocumentTimeline" | "DocumentType" | "DragEvent" | "DynamicsCompressorNode" | "Element" | "ElementInternals" | "EncodedAudioChunk" | "EncodedVideoChunk" | "ErrorEvent" | "Event" | "EventCounts" | "EventSource" | "EventTarget" | "External" | "File" | "FileList" | "FileReader" | "FileSystem" | "FileSystemDirectoryEntry" | "FileSystemDirectoryHandle" | "FileSystemDirectoryReader" | "FileSystemEntry" | "FileSystemFileEntry" | "FileSystemFileHandle" | "FileSystemHandle" | "FileSystemWritableFileStream" | "FocusEvent" | "FontFace" | "FontFaceSet" | "FontFaceSetLoadEvent" | "FormData" | "FormDataEvent" | "FragmentDirective" | "GainNode" | "Gamepad" | "GamepadButton" | "GamepadEvent" | "GamepadHapticActuator" | "Geolocation" | "GeolocationCoordinates" | "GeolocationPosition" | "GeolocationPositionError" | "HTMLAllCollection" | "HTMLAnchorElement" | "HTMLAreaElement" | "HTMLAudioElement" | "HTMLBRElement" | "HTMLBaseElement" | "HTMLBodyElement" | "HTMLButtonElement" | "HTMLCanvasElement" | "HTMLCollection" | "HTMLDListElement" | "HTMLDataElement" | "HTMLDataListElement" | "HTMLDetailsElement" | "HTMLDialogElement" | "HTMLDirectoryElement" | "HTMLDivElement" | "HTMLDocument" | "HTMLElement" | "HTMLEmbedElement" | "HTMLFieldSetElement" | "HTMLFontElement" | "HTMLFormControlsCollection" | "HTMLFormElement" | "HTMLFrameElement" | "HTMLFrameSetElement" | "HTMLHRElement" | "HTMLHeadElement" | "HTMLHeadingElement" | "HTMLHtmlElement" | "HTMLIFrameElement" | "HTMLImageElement" | "HTMLInputElement" | "HTMLLIElement" | "HTMLLabelElement" | "HTMLLegendElement" | "HTMLLinkElement" | "HTMLMapElement" | "HTMLMarqueeElement" | "HTMLMediaElement" | "HTMLMenuElement" | "HTMLMetaElement" | "HTMLMeterElement" | "HTMLModElement" | "HTMLOListElement" | "HTMLObjectElement" | "HTMLOptGroupElement" | "HTMLOptionElement" | "HTMLOptionsCollection" | "HTMLOutputElement" | "HTMLParagraphElement" | "HTMLParamElement" | "HTMLPictureElement" | "HTMLPreElement" | "HTMLProgressElement" | "HTMLQuoteElement" | "HTMLScriptElement" | "HTMLSelectElement" | "HTMLSlotElement" | "HTMLSourceElement" | "HTMLSpanElement" | "HTMLStyleElement" | "HTMLTableCaptionElement" | "HTMLTableCellElement" | "HTMLTableColElement" | "HTMLTableElement" | "HTMLTableRowElement" | "HTMLTableSectionElement" | "HTMLTemplateElement" | "HTMLTextAreaElement" | "HTMLTimeElement" | "HTMLTitleElement" | "HTMLTrackElement" | "HTMLUListElement" | "HTMLUnknownElement" | "HTMLVideoElement" | "HashChangeEvent" | "Headers" | "Highlight" | "HighlightRegistry" | "History" | "IDBCursor" | "IDBCursorWithValue" | "IDBDatabase" | "IDBFactory" | "IDBIndex" | "IDBKeyRange" | "IDBObjectStore" | "IDBOpenDBRequest" | "IDBRequest" | "IDBTransaction" | "IDBVersionChangeEvent" | "IIRFilterNode" | "IdleDeadline" | "ImageBitmap" | "ImageBitmapRenderingContext" | "ImageCapture" | "ImageData" | "ImageDecoder" | "ImageTrack" | "ImageTrackList" | "InputDeviceInfo" | "InputEvent" | "IntersectionObserver" | "IntersectionObserverEntry" | "KeyboardEvent" | "KeyframeEffect" | "LargestContentfulPaint" | "Location" | "Lock" | "LockManager" | "MIDIAccess" | "MIDIConnectionEvent" | "MIDIInput" | "MIDIInputMap" | "MIDIMessageEvent" | "MIDIOutput" | "MIDIOutputMap" | "MIDIPort" | "MathMLElement" | "MediaCapabilities" | "MediaDeviceInfo" | "MediaDevices" | "MediaElementAudioSourceNode" | "MediaEncryptedEvent" | "MediaError" | "MediaKeyMessageEvent" | "MediaKeySession" | "MediaKeyStatusMap" | "MediaKeySystemAccess" | "MediaKeys" | "MediaList" | "MediaMetadata" | "MediaQueryList" | "MediaQueryListEvent" | "MediaRecorder" | "MediaSession" | "MediaSource" | "MediaSourceHandle" | "MediaStream" | "MediaStreamAudioDestinationNode" | "MediaStreamAudioSourceNode" | "MediaStreamTrack" | "MediaStreamTrackEvent" | "MessageChannel" | "MessageEvent" | "MessagePort" | "MimeType" | "MimeTypeArray" | "MouseEvent" | "MutationObserver" | "MutationRecord" | "NamedNodeMap" | "NavigationActivation" | "NavigationHistoryEntry" | "NavigationPreloadManager" | "Navigator" | "NavigatorLogin" | "Node" | "NodeIterator" | "NodeList" | "Notification" | "OfflineAudioCompletionEvent" | "OfflineAudioContext" | "OffscreenCanvas" | "OffscreenCanvasRenderingContext2D" | "OscillatorNode" | "OverconstrainedError" | "PageRevealEvent" | "PageSwapEvent" | "PageTransitionEvent" | "PannerNode" | "Path2D" | "PaymentAddress" | "PaymentMethodChangeEvent" | "PaymentRequest" | "PaymentRequestUpdateEvent" | "PaymentResponse" | "Performance" | "PerformanceEntry" | "PerformanceEventTiming" | "PerformanceMark" | "PerformanceMeasure" | "PerformanceNavigation" | "PerformanceNavigationTiming" | "PerformanceObserver" | "PerformanceObserverEntryList" | "PerformancePaintTiming" | "PerformanceResourceTiming" | "PerformanceServerTiming" | "PerformanceTiming" | "PeriodicWave" | "PermissionStatus" | "Permissions" | "PictureInPictureEvent" | "PictureInPictureWindow" | "Plugin" | "PluginArray" | "PointerEvent" | "PopStateEvent" | "ProcessingInstruction" | "ProgressEvent" | "PromiseRejectionEvent" | "PublicKeyCredential" | "PushManager" | "PushSubscription" | "PushSubscriptionOptions" | "RTCCertificate" | "RTCDTMFSender" | "RTCDTMFToneChangeEvent" | "RTCDataChannel" | "RTCDataChannelEvent" | "RTCDtlsTransport" | "RTCEncodedAudioFrame" | "RTCEncodedVideoFrame" | "RTCError" | "RTCErrorEvent" | "RTCIceCandidate" | "RTCIceTransport" | "RTCPeerConnection" | "RTCPeerConnectionIceErrorEvent" | "RTCPeerConnectionIceEvent" | "RTCRtpReceiver" | "RTCRtpScriptTransform" | "RTCRtpSender" | "RTCRtpTransceiver" | "RTCSctpTransport" | "RTCSessionDescription" | "RTCStatsReport" | "RTCTrackEvent" | "RadioNodeList" | "Range" | "ReadableByteStreamController" | "ReadableStream" | "ReadableStreamBYOBReader" | "ReadableStreamBYOBRequest" | "ReadableStreamDefaultController" | "ReadableStreamDefaultReader" | "RemotePlayback" | "Report" | "ReportBody" | "ReportingObserver" | "Request" | "ResizeObserver" | "ResizeObserverEntry" | "ResizeObserverSize" | "Response" | "SVGAElement" | "SVGAngle" | "SVGAnimateElement" | "SVGAnimateMotionElement" | "SVGAnimateTransformElement" | "SVGAnimatedAngle" | "SVGAnimatedBoolean" | "SVGAnimatedEnumeration" | "SVGAnimatedInteger" | "SVGAnimatedLength" | "SVGAnimatedLengthList" | "SVGAnimatedNumber" | "SVGAnimatedNumberList" | "SVGAnimatedPreserveAspectRatio" | "SVGAnimatedRect" | "SVGAnimatedString" | "SVGAnimatedTransformList" | "SVGAnimationElement" | "SVGCircleElement" | "SVGClipPathElement" | "SVGComponentTransferFunctionElement" | "SVGDefsElement" | "SVGDescElement" | "SVGElement" | "SVGEllipseElement" | "SVGFEBlendElement" | "SVGFEColorMatrixElement" | "SVGFEComponentTransferElement" | "SVGFECompositeElement" | "SVGFEConvolveMatrixElement" | "SVGFEDiffuseLightingElement" | "SVGFEDisplacementMapElement" | "SVGFEDistantLightElement" | "SVGFEDropShadowElement" | "SVGFEFloodElement" | "SVGFEFuncAElement" | "SVGFEFuncBElement" | "SVGFEFuncGElement" | "SVGFEFuncRElement" | "SVGFEGaussianBlurElement" | "SVGFEImageElement" | "SVGFEMergeElement" | "SVGFEMergeNodeElement" | "SVGFEMorphologyElement" | "SVGFEOffsetElement" | "SVGFEPointLightElement" | "SVGFESpecularLightingElement" | "SVGFESpotLightElement" | "SVGFETileElement" | "SVGFETurbulenceElement" | "SVGFilterElement" | "SVGForeignObjectElement" | "SVGGElement" | "SVGGeometryElement" | "SVGGradientElement" | "SVGGraphicsElement" | "SVGImageElement" | "SVGLength" | "SVGLengthList" | "SVGLineElement" | "SVGLinearGradientElement" | "SVGMPathElement" | "SVGMarkerElement" | "SVGMaskElement" | "SVGMetadataElement" | "SVGNumber" | "SVGNumberList" | "SVGPathElement" | "SVGPatternElement" | "SVGPointList" | "SVGPolygonElement" | "SVGPolylineElement" | "SVGPreserveAspectRatio" | "SVGRadialGradientElement" | "SVGRectElement" | "SVGSVGElement" | "SVGScriptElement" | "SVGSetElement" | "SVGStopElement" | "SVGStringList" | "SVGStyleElement" | "SVGSwitchElement" | "SVGSymbolElement" | "SVGTSpanElement" | "SVGTextContentElement" | "SVGTextElement" | "SVGTextPathElement" | "SVGTextPositioningElement" | "SVGTitleElement" | "SVGTransform" | "SVGTransformList" | "SVGUnitTypes" | "SVGUseElement" | "SVGViewElement" | "Screen" | "ScreenOrientation" | "ScriptProcessorNode" | "SecurityPolicyViolationEvent" | "Selection" | "ServiceWorker" | "ServiceWorkerContainer" | "ServiceWorkerRegistration" | "ShadowRoot" | "SharedWorker" | "SourceBuffer" | "SourceBufferList" | "SpeechRecognitionAlternative" | "SpeechRecognitionResult" | "SpeechRecognitionResultList" | "SpeechSynthesis" | "SpeechSynthesisErrorEvent" | "SpeechSynthesisEvent" | "SpeechSynthesisUtterance" | "SpeechSynthesisVoice" | "StaticRange" | "StereoPannerNode" | "Storage" | "StorageEvent" | "StorageManager" | "StylePropertyMap" | "StylePropertyMapReadOnly" | "StyleSheet" | "StyleSheetList" | "SubmitEvent" | "SubtleCrypto" | "Text" | "TextDecoder" | "TextDecoderStream" | "TextEncoder" | "TextEncoderStream" | "TextEvent" | "TextMetrics" | "TextTrack" | "TextTrackCue" | "TextTrackCueList" | "TextTrackList" | "TimeRanges" | "ToggleEvent" | "Touch" | "TouchEvent" | "TouchList" | "TrackEvent" | "TransformStream" | "TransformStreamDefaultController" | "TransitionEvent" | "TreeWalker" | "UIEvent" | "URL" | "webkitURL" | "URLSearchParams" | "UserActivation" | "VTTCue" | "VTTRegion" | "ValidityState" | "VideoColorSpace" | "VideoDecoder" | "VideoEncoder" | "VideoFrame" | "VideoPlaybackQuality" | "ViewTransition" | "ViewTransitionTypeSet" | "VisualViewport" | "WakeLock" | "WakeLockSentinel" | "WaveShaperNode" | "WebGL2RenderingContext" | "WebGLActiveInfo" | "WebGLBuffer" | "WebGLContextEvent" | "WebGLFramebuffer" | "WebGLProgram" | "WebGLQuery" | "WebGLRenderbuffer" | "WebGLRenderingContext" | "WebGLSampler" | "WebGLShader" | "WebGLShaderPrecisionFormat" | "WebGLSync" | "WebGLTexture" | "WebGLTransformFeedback" | "WebGLUniformLocation" | "WebGLVertexArrayObject" | "WebSocket" | "WebTransport" | "WebTransportBidirectionalStream" | "WebTransportDatagramDuplexStream" | "WebTransportError" | "WheelEvent" | "Window" | "Worker" | "Worklet" | "WritableStream" | "WritableStreamDefaultController" | "WritableStreamDefaultWriter" | "XMLDocument" | "XMLHttpRequest" | "XMLHttpRequestEventTarget" | "XMLHttpRequestUpload" | "XMLSerializer" | "XPathEvaluator" | "XPathExpression" | "XPathResult" | "XSLTProcessor" | "CSS" | "WebAssembly" | "console" | "Audio" | "Image" | "Option" | "clientInformation" | "closed" | "cookieStore" | "customElements" | "devicePixelRatio" | "document" | "event" | "external" | "frameElement" | "frames" | "history" | "innerHeight" | "innerWidth" | "length" | "location" | "locationbar" | "menubar" | "navigator" | "ondevicemotion" | "ondeviceorientation" | "ondeviceorientationabsolute" | "onorientationchange" | "opener" | "orientation" | "originAgentCluster" | "outerHeight" | "outerWidth" | "pageXOffset" | "pageYOffset" | "parent" | "personalbar" | "screen" | "screenLeft" | "screenTop" | "screenX" | "screenY" | "scrollX" | "scrollY" | "scrollbars" | "self" | "speechSynthesis" | "status" | "statusbar" | "toolbar" | "top" | "visualViewport" | "window" | "onabort" | "onanimationcancel" | "onanimationend" | "onanimationiteration" | "onanimationstart" | "onauxclick" | "onbeforeinput" | "onbeforematch" | "onbeforetoggle" | "onblur" | "oncancel" | "oncanplay" | "oncanplaythrough" | "onchange" | "onclick" | "onclose" | "oncontextlost" | "oncontextmenu" | "oncontextrestored" | "oncopy" | "oncuechange" | "oncut" | "ondblclick" | "ondrag" | "ondragend" | "ondragenter" | "ondragleave" | "ondragover" | "ondragstart" | "ondrop" | "ondurationchange" | "onemptied" | "onended" | "onerror" | "onfocus" | "onformdata" | "ongotpointercapture" | "oninput" | "oninvalid" | "onkeydown" | "onkeypress" | "onkeyup" | "onload" | "onloadeddata" | "onloadedmetadata" | "onloadstart" | "onlostpointercapture" | "onmousedown" | "onmouseenter" | "onmouseleave" | "onmousemove" | "onmouseout" | "onmouseover" | "onmouseup" | "onpaste" | "onpause" | "onplay" | "onplaying" | "onpointercancel" | "onpointerdown" | "onpointerenter" | "onpointerleave" | "onpointermove" | "onpointerout" | "onpointerover" | "onpointerrawupdate" | "onpointerup" | "onprogress" | "onratechange" | "onreset" | "onresize" | "onscroll" | "onscrollend" | "onsecuritypolicyviolation" | "onseeked" | "onseeking" | "onselect" | "onselectionchange" | "onselectstart" | "onslotchange" | "onstalled" | "onsubmit" | "onsuspend" | "ontimeupdate" | "ontoggle" | "ontouchcancel" | "ontouchend" | "ontouchmove" | "ontouchstart" | "ontransitioncancel" | "ontransitionend" | "ontransitionrun" | "ontransitionstart" | "onvolumechange" | "onwaiting" | "onwebkitanimationend" | "onwebkitanimationiteration" | "onwebkitanimationstart" | "onwebkittransitionend" | "onwheel" | "onafterprint" | "onbeforeprint" | "onbeforeunload" | "ongamepadconnected" | "ongamepaddisconnected" | "onhashchange" | "onlanguagechange" | "onmessage" | "onmessageerror" | "onoffline" | "ononline" | "onpagehide" | "onpagereveal" | "onpageshow" | "onpageswap" | "onpopstate" | "onrejectionhandled" | "onstorage" | "onunhandledrejection" | "onunload" | "localStorage" | "caches" | "crossOriginIsolated" | "crypto" | "indexedDB" | "isSecureContext" | "origin" | "performance" | "sessionStorage" | "importScripts" | "ActiveXObject" | "WScript" | "WSH" | "Enumerator" | "VBArray" | "Map" | "WeakMap" | "Set" | "WeakSet" | "Iterator" | "Proxy" | "Reflect" | "SharedArrayBuffer" | "Atomics" | "BigInt" | "BigInt64Array" | "BigUint64Array" | "AggregateError" | "WeakRef" | "FinalizationRegistry" | "SuppressedError" | "DisposableStack" | "AsyncDisposableStack" | "Float16Array") | "blob" | "file" | "formdata" | string;
|
|
8
|
+
/**
|
|
9
|
+
* 判断值是否为原生 Blob(含 File)。
|
|
10
|
+
*
|
|
11
|
+
* @param {*} obj - 待检测的值
|
|
12
|
+
* @returns {obj is Blob}
|
|
13
|
+
*/
|
|
14
|
+
declare function isBlob(obj: any): obj is Blob;
|
|
15
|
+
/**
|
|
16
|
+
* 判断值是否为**纯粹**的 Object(即 `{}` 或 `new Object()`,不含数组、null、自定义类等)。
|
|
17
|
+
*
|
|
18
|
+
* @param {*} obj - 待检测的值
|
|
19
|
+
* @returns {obj is Record<PropertyKey, any>}
|
|
20
|
+
*/
|
|
21
|
+
declare function isPlainObject(obj: any): obj is Record<PropertyKey, any>;
|
|
22
|
+
/**
|
|
23
|
+
* 判断值是否为 Promise(含 Promise 子类)。
|
|
24
|
+
*
|
|
25
|
+
* @param {*} obj - 待检测的值
|
|
26
|
+
* @returns {obj is Promise<any>}
|
|
27
|
+
*/
|
|
28
|
+
declare function isPromise(obj: any): obj is Promise<any>;
|
|
29
|
+
/**
|
|
30
|
+
* 判断值是否为合法 Date 对象(含 Invalid Date 返回 false)。
|
|
31
|
+
*
|
|
32
|
+
* @param {*} t - 待检测值
|
|
33
|
+
* @returns {t is Date}
|
|
34
|
+
*/
|
|
35
|
+
declare function isDate(t: any): t is Date;
|
|
36
|
+
/**
|
|
37
|
+
* 判断值是否为函数(含异步函数、生成器函数、类)。
|
|
38
|
+
*
|
|
39
|
+
* @param {*} obj - 待检测的值
|
|
40
|
+
* @returns {obj is Function}
|
|
41
|
+
*/
|
|
42
|
+
declare function isFunction(obj: any): obj is Function;
|
|
43
|
+
/**
|
|
44
|
+
* 判断值是否为**非空**字符串。
|
|
45
|
+
*
|
|
46
|
+
* @param {*} obj - 待检测的值
|
|
47
|
+
* @returns {obj is string}
|
|
48
|
+
*/
|
|
49
|
+
declare function isNonEmptyString(obj: any): obj is string;
|
|
50
|
+
/**
|
|
51
|
+
* 在闭区间 [min, max] 内生成一个均匀分布的随机整数。
|
|
52
|
+
* 若 min > max 则自动交换。
|
|
53
|
+
*
|
|
54
|
+
* @param {number} min - 整数下界(包含)
|
|
55
|
+
* @param {number} max - 整数上界(包含)
|
|
56
|
+
* @returns {number}
|
|
57
|
+
* @throws {TypeError} 当 min 或 max 不是整数时抛出
|
|
58
|
+
*/
|
|
59
|
+
declare function randomIntInRange(min: number, max: number): number;
|
|
60
|
+
/**
|
|
61
|
+
* 随机生成一个汉字(可控制范围)。
|
|
62
|
+
*
|
|
63
|
+
* @param {boolean} [base=true] - 是否启用基本区(0x4E00-0x9FA5)
|
|
64
|
+
* @param {boolean} [extA=false] - 是否启用扩展 A 区(0x3400-0x4DBF)
|
|
65
|
+
* @param {boolean} [extBH=false] - 是否启用扩展 B~H 区(0x20000-0x2EBEF,代理对)
|
|
66
|
+
* @returns {string} 单个汉字字符
|
|
67
|
+
* @throws {RangeError} 未启用任何区段时抛出
|
|
68
|
+
*/
|
|
69
|
+
declare function randomHan(base?: boolean, extA?: boolean, extBH?: boolean): string;
|
|
70
|
+
/**
|
|
71
|
+
* 随机生成一个英文字母。
|
|
72
|
+
*
|
|
73
|
+
* @param {'lower'|'upper'} [type] - 指定大小写;留空则随机
|
|
74
|
+
* @returns {string} 单个字母
|
|
75
|
+
*/
|
|
76
|
+
declare function randomEnLetter(type?: "lower" | "upper"): string;
|
|
77
|
+
/**
|
|
78
|
+
* 生成指定长度的随机“中英混合”字符串。
|
|
79
|
+
*
|
|
80
|
+
* @param {number} [len=1] - 目标长度(≥1,自动取整)
|
|
81
|
+
* @param {number} [zhProb=0.5] - 每个位置选择汉字的概率,默认 0.5
|
|
82
|
+
* @returns {string}
|
|
83
|
+
*/
|
|
84
|
+
declare function randomHanOrEn(len?: number, zhProb?: number): string;
|
|
85
|
+
/**
|
|
86
|
+
* 创建 debounced(防抖)函数。
|
|
87
|
+
* - 默认 trailing 触发;当 `leading=true` 时,首次调用或超过等待间隔会立即执行。
|
|
88
|
+
* - 支持手动取消。
|
|
89
|
+
*
|
|
90
|
+
* @template {(...args: any[]) => any} T
|
|
91
|
+
* @param {T} fn - 要防抖的原始函数
|
|
92
|
+
* @param {number} wait - 防抖等待时间(毫秒)
|
|
93
|
+
* @param {boolean} [leading=false] - 是否启用立即执行(leading edge)
|
|
94
|
+
* @returns {T & { cancel(): void }} 返回经过防抖包装的函数,并附带 `cancel` 方法
|
|
95
|
+
* @throws {TypeError} 当 `fn` 不是函数时抛出
|
|
96
|
+
*/
|
|
97
|
+
declare function debounce<T extends (...args: any[]) => any>(fn: T, wait: number, leading?: boolean): T & {
|
|
98
|
+
cancel(): void;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* 创建 throttled(节流)函数。
|
|
102
|
+
* 支持 leading/trailing 边缘触发,可手动取消。
|
|
103
|
+
*
|
|
104
|
+
* @template {(...args: any[]) => any} T
|
|
105
|
+
* @param {T} fn - 要节流的原始函数
|
|
106
|
+
* @param {number} wait - 节流间隔(毫秒)
|
|
107
|
+
* @param {object} [options] - 配置项
|
|
108
|
+
* @param {boolean} [options.leading=true] - 是否在 leading 边缘执行
|
|
109
|
+
* @param {boolean} [options.trailing=true] - 是否在 trailing 边缘执行
|
|
110
|
+
* @returns {T & { cancel(): void }} 返回经过节流包装的函数,并附带 `cancel` 方法
|
|
111
|
+
* @throws {TypeError} 当 `fn` 不是函数时抛出
|
|
112
|
+
*/
|
|
113
|
+
declare function throttle<T extends (...args: any[]) => any>(fn: T, wait: number, { leading, trailing }?: {
|
|
114
|
+
leading?: boolean | undefined;
|
|
115
|
+
trailing?: boolean | undefined;
|
|
116
|
+
}): T & {
|
|
117
|
+
cancel(): void;
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* 利用 JSON 序列化/反序列化实现**深拷贝**。
|
|
121
|
+
* 注意:会丢失 `undefined`、函数、循环引用、特殊包装对象等。
|
|
122
|
+
*
|
|
123
|
+
* @template T
|
|
124
|
+
* @param {T} obj - 待拷贝的 JSON 兼容值
|
|
125
|
+
* @returns {T} 深拷贝后的值
|
|
126
|
+
*/
|
|
127
|
+
declare function deepCloneByJSON<T>(obj: T): T;
|
|
128
|
+
/**
|
|
129
|
+
* **安全**地将源对象中**已存在**的属性赋值到目标对象。
|
|
130
|
+
* 不会新增键,也不会复制原型链上的属性。
|
|
131
|
+
*
|
|
132
|
+
* @template {Record<PropertyKey, any>} T
|
|
133
|
+
* @param {T} target - 目标对象(将被就地修改)
|
|
134
|
+
* @param {...Partial<T>} sources - 一个或多个源对象
|
|
135
|
+
* @returns {T} 修改后的目标对象(即第一个参数本身)
|
|
136
|
+
*
|
|
137
|
+
* @example
|
|
138
|
+
* const defaults = { a: 1, b: 2 };
|
|
139
|
+
* assignExisting(defaults, { a: 9, c: 99 }); // defaults 变为 { a: 9, b: 2 }
|
|
140
|
+
*/
|
|
141
|
+
declare function assignExisting<T extends Record<PropertyKey, any>>(target: T, ...sources: Partial<T>[]): T;
|
|
142
|
+
/**
|
|
143
|
+
* 提取任意函数(含箭头函数、普通函数、async、class 构造器)的形参名称列表。
|
|
144
|
+
* 通过源码正则解析,不支持解构参数、默认参数、剩余参数等复杂语法;
|
|
145
|
+
* 若出现上述场景将返回空数组或部分名称。
|
|
146
|
+
*
|
|
147
|
+
* @param {Function} fn - 目标函数
|
|
148
|
+
* @returns {string[]} 按声明顺序排列的参数名数组;解析失败时返回空数组
|
|
149
|
+
*
|
|
150
|
+
* @example
|
|
151
|
+
* getFunctionArgNames(function (a, b) {}) // ["a", "b"]
|
|
152
|
+
* getFunctionArgNames((foo, bar) => {}) // ["foo", "bar"]
|
|
153
|
+
* getFunctionArgNames(async function x({a} = {}) {}) // [] (解构无法识别)
|
|
154
|
+
*/
|
|
155
|
+
declare function getFunctionArgNames(fn: Function): string[];
|
|
156
|
+
/**
|
|
157
|
+
* 将 Blob(或 File)读取为文本,并可选择自动执行 `JSON.parse`。
|
|
158
|
+
* 当 `isParse=true` 且内容非法 JSON 时,会回退为返回原始文本。
|
|
159
|
+
*
|
|
160
|
+
* @param {Blob} blob - 待读取的 Blob/File 对象
|
|
161
|
+
* @param {boolean} [isParse=true] - 是否尝试将结果按 JSON 解析
|
|
162
|
+
* @returns {Promise<string | any>} 解析后的 JSON 对象或原始文本
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* const json = await readBlobAsText(blob); // 自动 JSON.parse
|
|
166
|
+
* const text = await readBlobAsText(blob, false); // 仅返回文本
|
|
167
|
+
*/
|
|
168
|
+
declare function readBlobAsText(blob: Blob, isParse?: boolean): Promise<string | any>;
|
|
169
|
+
|
|
170
|
+
export { assignExisting, debounce, deepCloneByJSON, getDataType, getFunctionArgNames, isBlob, isDate, isFunction, isNonEmptyString, isPlainObject, isPromise, randomEnLetter, randomHan, randomHanOrEn, randomIntInRange, readBlobAsText, throttle };
|
package/types/date.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 将任意值安全转换为 Date 对象。
|
|
3
|
+
* - 数字/数字字符串:视为时间戳
|
|
4
|
+
* - 字符串:尝试按 ISO/RFC 格式解析
|
|
5
|
+
* - 对象:优先 valueOf(),再 toString()
|
|
6
|
+
* - null / undefined / 无效值:返回 null
|
|
7
|
+
*
|
|
8
|
+
* @param {*} val - 待转换值
|
|
9
|
+
* @returns {Date | null} 有效 Date 或 null
|
|
10
|
+
*/
|
|
11
|
+
declare function toDate(val: any): Date | null;
|
|
12
|
+
/**
|
|
13
|
+
* 在闭区间 [date1, date2] 内随机生成一个日期(含首尾)。
|
|
14
|
+
* 若顺序相反则自动交换。
|
|
15
|
+
*
|
|
16
|
+
* @param {Date} date1 - 起始日期
|
|
17
|
+
* @param {Date} date2 - 结束日期
|
|
18
|
+
* @returns {Date} 随机日期
|
|
19
|
+
*/
|
|
20
|
+
declare function randomDateInRange(date1: Date, date2: Date): Date;
|
|
21
|
+
/**
|
|
22
|
+
* 计算两个时间之间的剩余/已过时长(天-时-分-秒),返回带补零的展示对象。
|
|
23
|
+
*
|
|
24
|
+
* @param {string|number|Date} originalTime - 原始时间(可转 Date 的任意值)
|
|
25
|
+
* @param {Date} [currentTime=new Date()] - 基准时间,默认当前
|
|
26
|
+
* @returns {{days:number,hours:string,minutes:string,seconds:string}}
|
|
27
|
+
*/
|
|
28
|
+
declare function calcTimeDifference(originalTime: string | number | Date, currentTime?: Date): {
|
|
29
|
+
days: number;
|
|
30
|
+
hours: string;
|
|
31
|
+
minutes: string;
|
|
32
|
+
seconds: string;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* 将总秒数格式化成人类可读的时间段文本。
|
|
36
|
+
* 固定进制:1 年=365 天,1 月=30 天。
|
|
37
|
+
*
|
|
38
|
+
* @param {number} totalSeconds - 非负总秒数
|
|
39
|
+
* @param {object} [options] - 格式化选项
|
|
40
|
+
* @param {Partial<{year:string,month:string,day:string,hour:string,minute:string,second:string}>} [options.labels] - 各单位的自定义文本
|
|
41
|
+
* @param {('year'|'month'|'day'|'hour'|'minute'|'second')} [options.maxUnit] - 最大输出单位
|
|
42
|
+
* @param {('year'|'month'|'day'|'hour'|'minute'|'second')} [options.minUnit] - 最小输出单位
|
|
43
|
+
* @param {boolean} [options.showZero] - 是否强制显示 0 秒
|
|
44
|
+
* @returns {string} 拼接后的时长文本,如“1天 02小时 30分钟”
|
|
45
|
+
* @throws {TypeError} 当 totalSeconds 为非数字或负数时抛出
|
|
46
|
+
*/
|
|
47
|
+
declare function formatDuration(totalSeconds: number, options?: {
|
|
48
|
+
labels?: Partial<{
|
|
49
|
+
year: string;
|
|
50
|
+
month: string;
|
|
51
|
+
day: string;
|
|
52
|
+
hour: string;
|
|
53
|
+
minute: string;
|
|
54
|
+
second: string;
|
|
55
|
+
}> | undefined;
|
|
56
|
+
maxUnit?: "year" | "month" | "day" | "hour" | "minute" | "second" | undefined;
|
|
57
|
+
minUnit?: "year" | "month" | "day" | "hour" | "minute" | "second" | undefined;
|
|
58
|
+
showZero?: boolean | undefined;
|
|
59
|
+
}): string;
|
|
60
|
+
/**
|
|
61
|
+
* 快捷调用 {@link formatDuration},最大单位到“天”。
|
|
62
|
+
*
|
|
63
|
+
* @param {number} totalSeconds
|
|
64
|
+
* @param {Omit<Parameters<typeof formatDuration>[1],'maxUnit'>} [options]
|
|
65
|
+
* @returns {string}
|
|
66
|
+
*/
|
|
67
|
+
declare function formatDurationMaxDay(totalSeconds: number, options?: Omit<Parameters<typeof formatDuration>[1], "maxUnit">): string;
|
|
68
|
+
/**
|
|
69
|
+
* 快捷调用 {@link formatDuration},最大单位到“小时”。
|
|
70
|
+
*
|
|
71
|
+
* @param {number} totalSeconds
|
|
72
|
+
* @param {Omit<Parameters<typeof formatDuration>[1],'maxUnit'>} [options]
|
|
73
|
+
* @returns {string}
|
|
74
|
+
*/
|
|
75
|
+
declare function formatDurationMaxHour(totalSeconds: number, options?: Omit<Parameters<typeof formatDuration>[1], "maxUnit">): string;
|
|
76
|
+
|
|
77
|
+
export { calcTimeDifference, formatDuration, formatDurationMaxDay, formatDurationMaxHour, randomDateInRange, toDate };
|