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
|
@@ -0,0 +1,1070 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 使用 Fisher-Yates 算法对数组 **原地** 随机乱序。
|
|
3
|
+
* @template T
|
|
4
|
+
* @param {T[]} arr - 要乱序的数组
|
|
5
|
+
* @returns {T[]} 返回传入的同一数组实例(已乱序)
|
|
6
|
+
*/
|
|
7
|
+
function shuffle(arr) {
|
|
8
|
+
// 方式一:
|
|
9
|
+
// arr.sort(() => Math.random() - 0.5);
|
|
10
|
+
// 方式二:
|
|
11
|
+
for (let i = arr.length - 1; i > 0; i--) {
|
|
12
|
+
const j = Math.floor(Math.random() * (i + 1));
|
|
13
|
+
[arr[i], arr[j]] = [arr[j], arr[i]];
|
|
14
|
+
}
|
|
15
|
+
return arr;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 将数组中的元素从 `fromIndex` 移动到 `toIndex`,**原地** 修改并返回该数组。
|
|
20
|
+
* @template T
|
|
21
|
+
* @param {T[]} arr - 要操作的数组
|
|
22
|
+
* @param {number} fromIndex - 原始下标
|
|
23
|
+
* @param {number} toIndex - 目标下标
|
|
24
|
+
* @returns {T[]} 返回传入的同一数组实例
|
|
25
|
+
*/
|
|
26
|
+
function moveItem(arr, fromIndex, toIndex) {
|
|
27
|
+
arr.splice(toIndex, 0, arr.splice(fromIndex, 1)[0]);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 视口尺寸对象。
|
|
32
|
+
* @typedef {Object} ViewportDimensions
|
|
33
|
+
* @property {number} w 视口宽度,单位像素。
|
|
34
|
+
* @property {number} h 视口高度,单位像素。
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 获取当前视口(viewport)的宽高。
|
|
39
|
+
*
|
|
40
|
+
* 兼容策略:
|
|
41
|
+
* 1. 优先使用 `window.innerWidth/innerHeight`(现代浏览器)。
|
|
42
|
+
* 2. 降级到 `document.documentElement.clientWidth/clientHeight`(IE9+ 及怪异模式)。
|
|
43
|
+
* 3. 最后降级到 `document.body.clientWidth/clientHeight`(IE6-8 怪异模式)。
|
|
44
|
+
*
|
|
45
|
+
* @returns {ViewportDimensions} 包含 `w`(宽度)和 `h`(高度)的对象,单位为像素。
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* const { w, h } = getViewportSize();
|
|
49
|
+
* console.log(`视口尺寸:${w} × ${h}`);
|
|
50
|
+
*/
|
|
51
|
+
function getViewportSize() {
|
|
52
|
+
const d = document,
|
|
53
|
+
root = d.documentElement,
|
|
54
|
+
body = d.body;
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
w: window.innerWidth || root.clientWidth || body.clientWidth,
|
|
58
|
+
h: window.innerHeight || root.clientHeight || body.clientHeight
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 将当前页面 URL 的 query 部分解析成键值对对象。
|
|
64
|
+
*
|
|
65
|
+
* @returns {Record<string, string>} 所有查询参数组成的平凡对象
|
|
66
|
+
* (同名 key 仅保留最后一项)
|
|
67
|
+
*/
|
|
68
|
+
function getAllSearchParams() {
|
|
69
|
+
const urlSearchParams = new URLSearchParams(location.search);
|
|
70
|
+
return Object.fromEntries(urlSearchParams.entries());
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 根据 key 获取当前页面 URL 中的单个查询参数。
|
|
75
|
+
*
|
|
76
|
+
* @param {string} key - 要提取的参数名
|
|
77
|
+
* @returns {string | undefined} 对应参数值;不存在时返回 `undefined`
|
|
78
|
+
*/
|
|
79
|
+
function getSearchParam(key) {
|
|
80
|
+
const params = getAllSearchParams();
|
|
81
|
+
return params[key];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
//#region 数据类型判断
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 返回任意值的运行时类型字符串(小写形式)。
|
|
88
|
+
*
|
|
89
|
+
* @param {*} obj 待检测的值
|
|
90
|
+
* @returns {keyof globalThis|"blob"|"file"|"formdata"|string} 小写类型名
|
|
91
|
+
*/
|
|
92
|
+
function getDataType(obj) {
|
|
93
|
+
return Object.prototype.toString
|
|
94
|
+
.call(obj)
|
|
95
|
+
.replace(/^\[object\s(\w+)\]$/, "$1")
|
|
96
|
+
.toLowerCase();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 判断值是否为原生 Blob(含 File)。
|
|
101
|
+
*
|
|
102
|
+
* @param {*} obj - 待检测的值
|
|
103
|
+
* @returns {obj is Blob}
|
|
104
|
+
*/
|
|
105
|
+
function isBlob(obj) {
|
|
106
|
+
return getDataType(obj) === "blob";
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 判断值是否为**纯粹**的 Object(即 `{}` 或 `new Object()`,不含数组、null、自定义类等)。
|
|
111
|
+
*
|
|
112
|
+
* @param {*} obj - 待检测的值
|
|
113
|
+
* @returns {obj is Record<PropertyKey, any>}
|
|
114
|
+
*/
|
|
115
|
+
function isPlainObject(obj) {
|
|
116
|
+
return getDataType(obj) === "object";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 判断值是否为 Promise(含 Promise 子类)。
|
|
121
|
+
*
|
|
122
|
+
* @param {*} obj - 待检测的值
|
|
123
|
+
* @returns {obj is Promise<any>}
|
|
124
|
+
*/
|
|
125
|
+
function isPromise(obj) {
|
|
126
|
+
return getDataType(obj) === "promise";
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 判断值是否为合法 Date 对象(含 Invalid Date 返回 false)。
|
|
131
|
+
*
|
|
132
|
+
* @param {*} t - 待检测值
|
|
133
|
+
* @returns {t is Date}
|
|
134
|
+
*/
|
|
135
|
+
function isDate(t) {
|
|
136
|
+
return getDataType(t) === "date";
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* 判断值是否为函数(含异步函数、生成器函数、类)。
|
|
141
|
+
*
|
|
142
|
+
* @param {*} obj - 待检测的值
|
|
143
|
+
* @returns {obj is Function}
|
|
144
|
+
*/
|
|
145
|
+
function isFunction(obj) {
|
|
146
|
+
return typeof obj === "function";
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* 判断值是否为**非空**字符串。
|
|
151
|
+
*
|
|
152
|
+
* @param {*} obj - 待检测的值
|
|
153
|
+
* @returns {obj is string}
|
|
154
|
+
*/
|
|
155
|
+
function isNonEmptyString(obj) {
|
|
156
|
+
return getDataType(obj) === "string" && obj.length > 0;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
//#endregion
|
|
160
|
+
|
|
161
|
+
//#region 随机数据
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 在闭区间 [min, max] 内生成一个均匀分布的随机整数。
|
|
165
|
+
* 若 min > max 则自动交换。
|
|
166
|
+
*
|
|
167
|
+
* @param {number} min - 整数下界(包含)
|
|
168
|
+
* @param {number} max - 整数上界(包含)
|
|
169
|
+
* @returns {number}
|
|
170
|
+
* @throws {TypeError} 当 min 或 max 不是整数时抛出
|
|
171
|
+
*/
|
|
172
|
+
function randomIntInRange(min, max) {
|
|
173
|
+
if (!Number.isInteger(min) || !Number.isInteger(max)) {
|
|
174
|
+
throw new TypeError("Arguments must be integers");
|
|
175
|
+
}
|
|
176
|
+
if (min > max) [min, max] = [max, min];
|
|
177
|
+
// 注意加 1,否则 max 永远取不到;Math.floor 保证均匀
|
|
178
|
+
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* 随机生成一个汉字(可控制范围)。
|
|
183
|
+
*
|
|
184
|
+
* @param {boolean} [base=true] - 是否启用基本区(0x4E00-0x9FA5)
|
|
185
|
+
* @param {boolean} [extA=false] - 是否启用扩展 A 区(0x3400-0x4DBF)
|
|
186
|
+
* @param {boolean} [extBH=false] - 是否启用扩展 B~H 区(0x20000-0x2EBEF,代理对)
|
|
187
|
+
* @returns {string} 单个汉字字符
|
|
188
|
+
* @throws {RangeError} 未启用任何区段时抛出
|
|
189
|
+
*/
|
|
190
|
+
function randomHan(base = true, extA = false, extBH = false) {
|
|
191
|
+
// 1. 收集已启用的“区段”
|
|
192
|
+
const ranges = [];
|
|
193
|
+
if (base) ranges.push({ min: 0x4e00, max: 0x9fa5, surrogate: false });
|
|
194
|
+
if (extA) ranges.push({ min: 0x3400, max: 0x4dbf, surrogate: false });
|
|
195
|
+
if (extBH) ranges.push({ min: 0x20000, max: 0x2ebef, surrogate: true });
|
|
196
|
+
|
|
197
|
+
if (ranges.length === 0) {
|
|
198
|
+
throw new RangeError("At least one range must be enabled");
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// 2. 按总码位数抽号
|
|
202
|
+
const total = ranges.reduce((sum, r) => sum + (r.max - r.min + 1), 0);
|
|
203
|
+
let n = randomIntInRange(0, total - 1);
|
|
204
|
+
|
|
205
|
+
// 3. 定位落在哪个区段
|
|
206
|
+
for (const { min, max, surrogate } of ranges) {
|
|
207
|
+
const size = max - min + 1;
|
|
208
|
+
if (n < size) {
|
|
209
|
+
const code = min + n;
|
|
210
|
+
if (!surrogate) return String.fromCharCode(code);
|
|
211
|
+
// 代理对
|
|
212
|
+
const offset = code - 0x10000;
|
|
213
|
+
const hi = (offset >> 10) + 0xd800;
|
|
214
|
+
const lo = (offset & 0x3ff) + 0xdc00;
|
|
215
|
+
return String.fromCharCode(hi, lo);
|
|
216
|
+
}
|
|
217
|
+
n -= size;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* 随机生成一个英文字母。
|
|
223
|
+
*
|
|
224
|
+
* @param {'lower'|'upper'} [type] - 指定大小写;留空则随机
|
|
225
|
+
* @returns {string} 单个字母
|
|
226
|
+
*/
|
|
227
|
+
function randomEnLetter(type) {
|
|
228
|
+
const lower = "abcdefghijklmnopqrstuvwxyz";
|
|
229
|
+
const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
230
|
+
const randomNum = randomIntInRange(0, 25);
|
|
231
|
+
|
|
232
|
+
switch (type) {
|
|
233
|
+
case "lower":
|
|
234
|
+
return lower[randomNum];
|
|
235
|
+
case "upper":
|
|
236
|
+
return upper[randomNum];
|
|
237
|
+
default:
|
|
238
|
+
return (Math.random() < 0.5 ? lower : upper)[randomNum];
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* 生成指定长度的随机“中英混合”字符串。
|
|
244
|
+
*
|
|
245
|
+
* @param {number} [len=1] - 目标长度(≥1,自动取整)
|
|
246
|
+
* @param {number} [zhProb=0.5] - 每个位置选择汉字的概率,默认 0.5
|
|
247
|
+
* @returns {string}
|
|
248
|
+
*/
|
|
249
|
+
function randomHanOrEn(len, zhProb = 0.5) {
|
|
250
|
+
len = Math.max(1, Math.floor(len));
|
|
251
|
+
const buf = [];
|
|
252
|
+
for (let i = 0; i < len; i++) {
|
|
253
|
+
buf.push(Math.random() < zhProb ? randomHan() : randomEnLetter());
|
|
254
|
+
}
|
|
255
|
+
return buf.join("");
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
//#endregion
|
|
259
|
+
|
|
260
|
+
//#region 防抖节流
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* 创建 debounced(防抖)函数。
|
|
264
|
+
* - 默认 trailing 触发;当 `leading=true` 时,首次调用或超过等待间隔会立即执行。
|
|
265
|
+
* - 支持手动取消。
|
|
266
|
+
*
|
|
267
|
+
* @template {(...args: any[]) => any} T
|
|
268
|
+
* @param {T} fn - 要防抖的原始函数
|
|
269
|
+
* @param {number} wait - 防抖等待时间(毫秒)
|
|
270
|
+
* @param {boolean} [leading=false] - 是否启用立即执行(leading edge)
|
|
271
|
+
* @returns {T & { cancel(): void }} 返回经过防抖包装的函数,并附带 `cancel` 方法
|
|
272
|
+
* @throws {TypeError} 当 `fn` 不是函数时抛出
|
|
273
|
+
*/
|
|
274
|
+
function debounce(fn, wait, leading = false) {
|
|
275
|
+
if (typeof fn !== "function") throw new TypeError("fn must be function");
|
|
276
|
+
wait = Math.max(0, Number(wait) || 0);
|
|
277
|
+
let timeoutId;
|
|
278
|
+
let lastCall = 0; // 0 表示从未调用过
|
|
279
|
+
|
|
280
|
+
function debounced(...args) {
|
|
281
|
+
const isFirst = lastCall === 0;
|
|
282
|
+
const isOverWait = Date.now() - lastCall >= wait;
|
|
283
|
+
|
|
284
|
+
clearTimeout(timeoutId);
|
|
285
|
+
|
|
286
|
+
// 首次调用 || 已达到等待间隔
|
|
287
|
+
if (leading && (isFirst || isOverWait)) {
|
|
288
|
+
lastCall = Date.now();
|
|
289
|
+
return fn.apply(this, args);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
timeoutId = setTimeout(() => {
|
|
293
|
+
lastCall = Date.now();
|
|
294
|
+
fn.apply(this, args);
|
|
295
|
+
}, wait);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
debounced.cancel = () => {
|
|
299
|
+
clearTimeout(timeoutId);
|
|
300
|
+
lastCall = 0; // 恢复初始状态
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
return debounced;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* 创建 throttled(节流)函数。
|
|
308
|
+
* 支持 leading/trailing 边缘触发,可手动取消。
|
|
309
|
+
*
|
|
310
|
+
* @template {(...args: any[]) => any} T
|
|
311
|
+
* @param {T} fn - 要节流的原始函数
|
|
312
|
+
* @param {number} wait - 节流间隔(毫秒)
|
|
313
|
+
* @param {object} [options] - 配置项
|
|
314
|
+
* @param {boolean} [options.leading=true] - 是否在 leading 边缘执行
|
|
315
|
+
* @param {boolean} [options.trailing=true] - 是否在 trailing 边缘执行
|
|
316
|
+
* @returns {T & { cancel(): void }} 返回经过节流包装的函数,并附带 `cancel` 方法
|
|
317
|
+
* @throws {TypeError} 当 `fn` 不是函数时抛出
|
|
318
|
+
*/
|
|
319
|
+
function throttle(fn, wait, { leading = true, trailing = true } = {}) {
|
|
320
|
+
if (typeof fn !== "function") throw new TypeError("fn must be function");
|
|
321
|
+
wait = Math.max(0, Number(wait) || 0);
|
|
322
|
+
|
|
323
|
+
let timeoutId = null,
|
|
324
|
+
lastCall = 0;
|
|
325
|
+
|
|
326
|
+
function throttled(...args) {
|
|
327
|
+
const remaining = wait - (Date.now() - lastCall);
|
|
328
|
+
|
|
329
|
+
if (leading && (lastCall === 0 || remaining <= 0)) {
|
|
330
|
+
lastCall = Date.now();
|
|
331
|
+
fn.apply(this, args);
|
|
332
|
+
} else if (trailing && !timeoutId) {
|
|
333
|
+
timeoutId = setTimeout(
|
|
334
|
+
() => {
|
|
335
|
+
timeoutId = null;
|
|
336
|
+
lastCall = Date.now();
|
|
337
|
+
fn.apply(this, args);
|
|
338
|
+
},
|
|
339
|
+
remaining > 0 ? remaining : wait
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
throttled.cancel = () => {
|
|
345
|
+
clearTimeout(timeoutId);
|
|
346
|
+
timeoutId = null;
|
|
347
|
+
lastCall = 0;
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
return throttled;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
//#endregion
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* 利用 JSON 序列化/反序列化实现**深拷贝**。
|
|
357
|
+
* 注意:会丢失 `undefined`、函数、循环引用、特殊包装对象等。
|
|
358
|
+
*
|
|
359
|
+
* @template T
|
|
360
|
+
* @param {T} obj - 待拷贝的 JSON 兼容值
|
|
361
|
+
* @returns {T} 深拷贝后的值
|
|
362
|
+
*/
|
|
363
|
+
function deepCloneByJSON(obj) {
|
|
364
|
+
return JSON.parse(JSON.stringify(obj));
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* **安全**地将源对象中**已存在**的属性赋值到目标对象。
|
|
369
|
+
* 不会新增键,也不会复制原型链上的属性。
|
|
370
|
+
*
|
|
371
|
+
* @template {Record<PropertyKey, any>} T
|
|
372
|
+
* @param {T} target - 目标对象(将被就地修改)
|
|
373
|
+
* @param {...Partial<T>} sources - 一个或多个源对象
|
|
374
|
+
* @returns {T} 修改后的目标对象(即第一个参数本身)
|
|
375
|
+
*
|
|
376
|
+
* @example
|
|
377
|
+
* const defaults = { a: 1, b: 2 };
|
|
378
|
+
* assignExisting(defaults, { a: 9, c: 99 }); // defaults 变为 { a: 9, b: 2 }
|
|
379
|
+
*/
|
|
380
|
+
function assignExisting(target, ...sources) {
|
|
381
|
+
sources.forEach((source) => {
|
|
382
|
+
Object.keys(source).forEach((key) => {
|
|
383
|
+
if (target.hasOwnProperty(key)) {
|
|
384
|
+
target[key] = source[key];
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
});
|
|
388
|
+
return target;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* 提取任意函数(含箭头函数、普通函数、async、class 构造器)的形参名称列表。
|
|
393
|
+
* 通过源码正则解析,不支持解构参数、默认参数、剩余参数等复杂语法;
|
|
394
|
+
* 若出现上述场景将返回空数组或部分名称。
|
|
395
|
+
*
|
|
396
|
+
* @param {Function} fn - 目标函数
|
|
397
|
+
* @returns {string[]} 按声明顺序排列的参数名数组;解析失败时返回空数组
|
|
398
|
+
*
|
|
399
|
+
* @example
|
|
400
|
+
* getFunctionArgNames(function (a, b) {}) // ["a", "b"]
|
|
401
|
+
* getFunctionArgNames((foo, bar) => {}) // ["foo", "bar"]
|
|
402
|
+
* getFunctionArgNames(async function x({a} = {}) {}) // [] (解构无法识别)
|
|
403
|
+
*/
|
|
404
|
+
function getFunctionArgNames(fn) {
|
|
405
|
+
const FN_ARG_SPLIT = /,/,
|
|
406
|
+
FN_ARG = /^\s*(_?)(\S+?)\1\s*$/,
|
|
407
|
+
FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m,
|
|
408
|
+
ARROW_ARG = /^([^(]+?)=>/,
|
|
409
|
+
STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;
|
|
410
|
+
|
|
411
|
+
const fnText = Function.prototype.toString.call(fn).replace(STRIP_COMMENTS, "");
|
|
412
|
+
const argDecl = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
|
|
413
|
+
const retArgNames = [];
|
|
414
|
+
[].forEach.call(argDecl[1].split(FN_ARG_SPLIT), function (arg) {
|
|
415
|
+
arg.replace(FN_ARG, function (all, underscore, name) {
|
|
416
|
+
retArgNames.push(name);
|
|
417
|
+
});
|
|
418
|
+
});
|
|
419
|
+
return retArgNames;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* 将 Blob(或 File)读取为文本,并可选择自动执行 `JSON.parse`。
|
|
424
|
+
* 当 `isParse=true` 且内容非法 JSON 时,会回退为返回原始文本。
|
|
425
|
+
*
|
|
426
|
+
* @param {Blob} blob - 待读取的 Blob/File 对象
|
|
427
|
+
* @param {boolean} [isParse=true] - 是否尝试将结果按 JSON 解析
|
|
428
|
+
* @returns {Promise<string | any>} 解析后的 JSON 对象或原始文本
|
|
429
|
+
*
|
|
430
|
+
* @example
|
|
431
|
+
* const json = await readBlobAsText(blob); // 自动 JSON.parse
|
|
432
|
+
* const text = await readBlobAsText(blob, false); // 仅返回文本
|
|
433
|
+
*/
|
|
434
|
+
function readBlobAsText(blob, isParse = true) {
|
|
435
|
+
return new Promise((resolve, reject) => {
|
|
436
|
+
const reader = new FileReader();
|
|
437
|
+
reader.onload = (evt) => {
|
|
438
|
+
const result = evt.target.result;
|
|
439
|
+
if (isParse) {
|
|
440
|
+
try {
|
|
441
|
+
resolve(JSON.parse(result));
|
|
442
|
+
} catch (error) {
|
|
443
|
+
console.error(error);
|
|
444
|
+
resolve(result);
|
|
445
|
+
}
|
|
446
|
+
} else {
|
|
447
|
+
resolve(result);
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
reader.onerror = reject;
|
|
451
|
+
reader.readAsText(blob);
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* 将任意值安全转换为 Date 对象。
|
|
457
|
+
* - 数字/数字字符串:视为时间戳
|
|
458
|
+
* - 字符串:尝试按 ISO/RFC 格式解析
|
|
459
|
+
* - 对象:优先 valueOf(),再 toString()
|
|
460
|
+
* - null / undefined / 无效值:返回 null
|
|
461
|
+
*
|
|
462
|
+
* @param {*} val - 待转换值
|
|
463
|
+
* @returns {Date | null} 有效 Date 或 null
|
|
464
|
+
*/
|
|
465
|
+
function toDate(val) {
|
|
466
|
+
if (val == null) return null; // null / undefined
|
|
467
|
+
if (val instanceof Date) return isNaN(val) ? null : val; // 已是 Date,但需排除 Invalid Date
|
|
468
|
+
|
|
469
|
+
// 1. 数字或数字字符串 → 时间戳
|
|
470
|
+
if (typeof val === "number" || (typeof val === "string" && /^-?\d+(\.\d+)?$/.test(val.trim()))) {
|
|
471
|
+
const d = new Date(+val);
|
|
472
|
+
return isNaN(d) ? null : d;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// 2. 标准 ISO 8601 / RFC 2825 等合法字符串
|
|
476
|
+
if (typeof val === "string") {
|
|
477
|
+
const d = new Date(val);
|
|
478
|
+
return isNaN(d) ? null : d; // 非法格式返回 null
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// 3. 对象带 valueOf / toString
|
|
482
|
+
if (typeof val === "object") {
|
|
483
|
+
// 优先调用 valueOf(期望返回数字时间戳)
|
|
484
|
+
const prim = val.valueOf ? val.valueOf() : Object.prototype.valueOf.call(val);
|
|
485
|
+
if (typeof prim === "number" && !isNaN(prim)) {
|
|
486
|
+
const d = new Date(prim);
|
|
487
|
+
return isNaN(d) ? null : d;
|
|
488
|
+
}
|
|
489
|
+
// 兜底用字符串
|
|
490
|
+
const str = val.toString ? val.toString() : String(val);
|
|
491
|
+
const d = new Date(str);
|
|
492
|
+
return isNaN(d) ? null : d;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// 4. 其余情况
|
|
496
|
+
return null;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* 在闭区间 [date1, date2] 内随机生成一个日期(含首尾)。
|
|
501
|
+
* 若顺序相反则自动交换。
|
|
502
|
+
*
|
|
503
|
+
* @param {Date} date1 - 起始日期
|
|
504
|
+
* @param {Date} date2 - 结束日期
|
|
505
|
+
* @returns {Date} 随机日期
|
|
506
|
+
*/
|
|
507
|
+
function randomDateInRange(date1, date2) {
|
|
508
|
+
let v1 = date1.getTime(),
|
|
509
|
+
v2 = date2.getTime();
|
|
510
|
+
if (v1 > v2) [v1, v2] = [v2, v1];
|
|
511
|
+
return new Date(v1 + Math.floor(Math.random() * (v2 - v1 + 1)));
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* 计算两个时间之间的剩余/已过时长(天-时-分-秒),返回带补零的展示对象。
|
|
516
|
+
*
|
|
517
|
+
* @param {string|number|Date} originalTime - 原始时间(可转 Date 的任意值)
|
|
518
|
+
* @param {Date} [currentTime=new Date()] - 基准时间,默认当前
|
|
519
|
+
* @returns {{days:number,hours:string,minutes:string,seconds:string}}
|
|
520
|
+
*/
|
|
521
|
+
function calcTimeDifference(originalTime, currentTime = new Date()) {
|
|
522
|
+
// 计算时间差(毫秒)
|
|
523
|
+
const diffMs = currentTime - new Date(originalTime);
|
|
524
|
+
|
|
525
|
+
// 转换为天、小时、分钟、秒
|
|
526
|
+
const diffSeconds = Math.floor(diffMs / 1000);
|
|
527
|
+
const days = Math.floor(diffSeconds / (3600 * 24));
|
|
528
|
+
const hours = Math.floor((diffSeconds % (3600 * 24)) / 3600);
|
|
529
|
+
const minutes = Math.floor((diffSeconds % 3600) / 60);
|
|
530
|
+
const seconds = diffSeconds % 60;
|
|
531
|
+
|
|
532
|
+
const padZero = (num) => String(num).padStart(2, "0");
|
|
533
|
+
|
|
534
|
+
return {
|
|
535
|
+
days,
|
|
536
|
+
hours: padZero(hours),
|
|
537
|
+
minutes: padZero(minutes),
|
|
538
|
+
seconds: padZero(seconds)
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* 将总秒数格式化成人类可读的时间段文本。
|
|
544
|
+
* 固定进制:1 年=365 天,1 月=30 天。
|
|
545
|
+
*
|
|
546
|
+
* @param {number} totalSeconds - 非负总秒数
|
|
547
|
+
* @param {object} [options] - 格式化选项
|
|
548
|
+
* @param {Partial<{year:string,month:string,day:string,hour:string,minute:string,second:string}>} [options.labels] - 各单位的自定义文本
|
|
549
|
+
* @param {('year'|'month'|'day'|'hour'|'minute'|'second')} [options.maxUnit] - 最大输出单位
|
|
550
|
+
* @param {('year'|'month'|'day'|'hour'|'minute'|'second')} [options.minUnit] - 最小输出单位
|
|
551
|
+
* @param {boolean} [options.showZero] - 是否强制显示 0 秒
|
|
552
|
+
* @returns {string} 拼接后的时长文本,如“1天 02小时 30分钟”
|
|
553
|
+
* @throws {TypeError} 当 totalSeconds 为非数字或负数时抛出
|
|
554
|
+
*/
|
|
555
|
+
function formatDuration(totalSeconds, options = {}) {
|
|
556
|
+
if (typeof totalSeconds !== "number" || totalSeconds < 0 || !isFinite(totalSeconds)) {
|
|
557
|
+
throw new TypeError("totalSeconds 必须是非负数字");
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// 1. 默认中文单位
|
|
561
|
+
const DEFAULT_LABELS = {
|
|
562
|
+
year: "年",
|
|
563
|
+
month: "月",
|
|
564
|
+
day: "天",
|
|
565
|
+
hour: "小时",
|
|
566
|
+
minute: "分钟",
|
|
567
|
+
second: "秒"
|
|
568
|
+
};
|
|
569
|
+
|
|
570
|
+
// 2. 固定进制表(秒)
|
|
571
|
+
const UNIT_TABLE = [
|
|
572
|
+
{ key: "year", seconds: 365 * 24 * 3600 },
|
|
573
|
+
{ key: "month", seconds: 30 * 24 * 3600 },
|
|
574
|
+
{ key: "day", seconds: 24 * 3600 },
|
|
575
|
+
{ key: "hour", seconds: 3600 },
|
|
576
|
+
{ key: "minute", seconds: 60 },
|
|
577
|
+
{ key: "second", seconds: 1 }
|
|
578
|
+
];
|
|
579
|
+
|
|
580
|
+
// 3. 合并用户自定义文本
|
|
581
|
+
const labels = Object.assign({}, DEFAULT_LABELS, options.labels);
|
|
582
|
+
|
|
583
|
+
// 4. 根据 maxUnit / minUnit 截取
|
|
584
|
+
let start = 0,
|
|
585
|
+
end = UNIT_TABLE.length;
|
|
586
|
+
if (options.maxUnit) {
|
|
587
|
+
const idx = UNIT_TABLE.findIndex((u) => u.key === options.maxUnit);
|
|
588
|
+
if (idx !== -1) start = idx;
|
|
589
|
+
}
|
|
590
|
+
if (options.minUnit) {
|
|
591
|
+
const idx = UNIT_TABLE.findIndex((u) => u.key === options.minUnit);
|
|
592
|
+
if (idx !== -1) end = idx + 1;
|
|
593
|
+
}
|
|
594
|
+
const units = UNIT_TABLE.slice(start, end);
|
|
595
|
+
if (!units.length) units.push(UNIT_TABLE[UNIT_TABLE.length - 1]); // 保底秒
|
|
596
|
+
|
|
597
|
+
// 5. 逐级计算
|
|
598
|
+
let rest = Math.floor(totalSeconds);
|
|
599
|
+
const parts = [];
|
|
600
|
+
|
|
601
|
+
for (const { key, seconds } of units) {
|
|
602
|
+
const val = Math.floor(rest / seconds);
|
|
603
|
+
rest %= seconds;
|
|
604
|
+
|
|
605
|
+
const shouldShow = val > 0 || (options.showZero && key === "second");
|
|
606
|
+
if (shouldShow || (parts.length === 0 && rest === 0)) {
|
|
607
|
+
parts.push(`${val}${labels[key]}`);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// 6. 兜底
|
|
612
|
+
if (parts.length === 0) {
|
|
613
|
+
parts.push(`0${labels[units[units.length - 1].key]}`);
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
return parts.join("");
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* 快捷调用 {@link formatDuration},最大单位到“天”。
|
|
621
|
+
*
|
|
622
|
+
* @param {number} totalSeconds
|
|
623
|
+
* @param {Omit<Parameters<typeof formatDuration>[1],'maxUnit'>} [options]
|
|
624
|
+
* @returns {string}
|
|
625
|
+
*/
|
|
626
|
+
function formatDurationMaxDay(totalSeconds, options = {}) {
|
|
627
|
+
return formatDuration(totalSeconds, { ...options, maxUnit: "day" });
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* 快捷调用 {@link formatDuration},最大单位到“小时”。
|
|
632
|
+
*
|
|
633
|
+
* @param {number} totalSeconds
|
|
634
|
+
* @param {Omit<Parameters<typeof formatDuration>[1],'maxUnit'>} [options]
|
|
635
|
+
* @returns {string}
|
|
636
|
+
*/
|
|
637
|
+
function formatDurationMaxHour(totalSeconds, options = {}) {
|
|
638
|
+
return formatDuration(totalSeconds, { ...options, maxUnit: "hour" });
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* 通过动态创建 `<a>` 标签触发浏览器下载。
|
|
643
|
+
*
|
|
644
|
+
* @param {string} url - 任意可下载地址(同源或允许跨域)
|
|
645
|
+
* @param {string} [fileName] - 保存到本地的文件名;不传时使用时间戳
|
|
646
|
+
*/
|
|
647
|
+
function downloadByUrl(url, fileName) {
|
|
648
|
+
const a = document.createElement("a");
|
|
649
|
+
a.style.display = "none";
|
|
650
|
+
a.rel = "noopener";
|
|
651
|
+
a.href = url;
|
|
652
|
+
a.download = fileName || Date.now();
|
|
653
|
+
document.body.appendChild(a);
|
|
654
|
+
a.click();
|
|
655
|
+
document.body.removeChild(a);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* 把 Blob 转成临时 URL 并触发下载,下载完成后立即释放内存。
|
|
660
|
+
*
|
|
661
|
+
* @param {Blob} blob - 待下载的 Blob(含 File)
|
|
662
|
+
* @param {string} [fileName] - 保存到本地的文件名
|
|
663
|
+
*/
|
|
664
|
+
function downloadByBlob(blob, fileName) {
|
|
665
|
+
const url = URL.createObjectURL(blob);
|
|
666
|
+
downloadByUrl(url, fileName);
|
|
667
|
+
setTimeout(() => URL.revokeObjectURL(url), 0);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/**
|
|
671
|
+
* 将任意数据包装成 Blob 并下载。
|
|
672
|
+
*
|
|
673
|
+
* @param {string | ArrayBufferView | ArrayBuffer | Blob} data - 要写入文件的数据
|
|
674
|
+
* @param {string} [fileName] - 保存到本地的文件名
|
|
675
|
+
* @param {string} [mimeType] - MIME 类型;默认 `application/octet-stream`
|
|
676
|
+
*/
|
|
677
|
+
function downloadByData(data, fileName, mimeType = "application/octet-stream") {
|
|
678
|
+
downloadByBlob(new Blob([data], { type: mimeType }), fileName);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* 快捷下载 Excel 文件(MIME 已固定)。
|
|
683
|
+
*
|
|
684
|
+
* @param {string | ArrayBufferView | ArrayBuffer | Blob} data - Excel 二进制或字符串内容
|
|
685
|
+
* @param {string} [fileName] - 保存到本地的文件名
|
|
686
|
+
*/
|
|
687
|
+
function downloadExcel(data, fileName) {
|
|
688
|
+
downloadByData(data, fileName, "application/vnd.ms-excel");
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* 快捷下载 JSON 文件(MIME 已固定)。
|
|
693
|
+
* 若传入非字符串数据,会自行 `JSON.stringify`。
|
|
694
|
+
*
|
|
695
|
+
* @param {any} data - 要序列化的 JSON 数据
|
|
696
|
+
* @param {string} [fileName] - 保存到本地的文件名
|
|
697
|
+
*/
|
|
698
|
+
function downloadJSON(data, fileName) {
|
|
699
|
+
// downloadByData(typeof data === "string" ? data : JSON.stringify(data, null, 4), fileName, "application/json");
|
|
700
|
+
downloadByData(data, fileName, "application/json");
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* 简单、高性能的通用事件总线。
|
|
705
|
+
* - 支持命名空间事件
|
|
706
|
+
* - 支持一次性监听器
|
|
707
|
+
* - 返回唯一 flag,用于精确卸载
|
|
708
|
+
* - emit 时可选自定义 this 指向
|
|
709
|
+
*/
|
|
710
|
+
class MyEvent {
|
|
711
|
+
constructor() {
|
|
712
|
+
this.evtPool = new Map();
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* 注册事件监听器。
|
|
717
|
+
* @param {string} name - 事件名
|
|
718
|
+
* @param {Function} fn - 回调函数
|
|
719
|
+
* @returns {string} flag - 唯一标识,用于 off
|
|
720
|
+
*/
|
|
721
|
+
on(name, fn) {
|
|
722
|
+
let flag = Date.now() + "_" + parseInt(Math.random() * 1e8);
|
|
723
|
+
const evtItem = {
|
|
724
|
+
flag,
|
|
725
|
+
fn
|
|
726
|
+
};
|
|
727
|
+
if (this.evtPool.has(name)) {
|
|
728
|
+
this.evtPool.get(name).push(evtItem);
|
|
729
|
+
} else {
|
|
730
|
+
this.evtPool.set(name, [evtItem]);
|
|
731
|
+
}
|
|
732
|
+
return flag;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* 注册一次性监听器,触发后自动移除。
|
|
737
|
+
* @param {string} name - 事件名
|
|
738
|
+
* @param {Function} fn - 回调函数
|
|
739
|
+
* @returns {string} flag - 唯一标识
|
|
740
|
+
*/
|
|
741
|
+
once(name, fn) {
|
|
742
|
+
const _this = this;
|
|
743
|
+
let wrapper;
|
|
744
|
+
wrapper = function (data) {
|
|
745
|
+
_this.off(name, wrapper);
|
|
746
|
+
fn.call(this, data);
|
|
747
|
+
};
|
|
748
|
+
return this.on(name, wrapper);
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* 移除指定事件监听器。
|
|
753
|
+
* @param {string} name - 事件名
|
|
754
|
+
* @param {Function|string} fnOrFlag - 回调函数或 flag
|
|
755
|
+
*/
|
|
756
|
+
off(name, fnOrFlag) {
|
|
757
|
+
if (!this.evtPool.has(name)) return;
|
|
758
|
+
const evtItems = this.evtPool.get(name);
|
|
759
|
+
const filtered = evtItems.filter((item) => item.fn !== fnOrFlag && item.flag !== fnOrFlag);
|
|
760
|
+
if (filtered.length === 0) {
|
|
761
|
+
this.evtPool.delete(name);
|
|
762
|
+
} else {
|
|
763
|
+
this.evtPool.set(name, filtered);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* 触发事件(同步执行)。
|
|
769
|
+
* @param {string} name - 事件名
|
|
770
|
+
* @param {*} [data] - 任意载荷
|
|
771
|
+
* @param {*} [fnThis] - 回调内部 this 指向,默认 undefined
|
|
772
|
+
*/
|
|
773
|
+
emit(name, data, fnThis) {
|
|
774
|
+
if (!this.evtPool.has(name)) return;
|
|
775
|
+
const evtItems = this.evtPool.get(name);
|
|
776
|
+
evtItems.forEach((item) => {
|
|
777
|
+
try {
|
|
778
|
+
item.fn.call(fnThis, data);
|
|
779
|
+
} catch (err) {
|
|
780
|
+
console.error(`Error in event listener for "${name}":`, err);
|
|
781
|
+
}
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* 跨页通信插件:通过 localStorage + storage 事件将当前实例的 emit 广播到其他同源页面。
|
|
788
|
+
* 支持节流、命名空间隔离。
|
|
789
|
+
*/
|
|
790
|
+
const MyEvent_CrossPagePlugin = (() => {
|
|
791
|
+
const INSTALLED = new WeakSet(); // 防止重复安装
|
|
792
|
+
|
|
793
|
+
return {
|
|
794
|
+
/**
|
|
795
|
+
* 为指定 MyEvent 实例安装跨页插件。
|
|
796
|
+
* @param {MyEvent} bus - 事件总线实例
|
|
797
|
+
* @param {Options} [opts] - 配置项
|
|
798
|
+
*/
|
|
799
|
+
install(bus, opts = {}) {
|
|
800
|
+
if (INSTALLED.has(bus)) return;
|
|
801
|
+
INSTALLED.add(bus);
|
|
802
|
+
|
|
803
|
+
const ns = `___my-event-cross-page-${opts.namespace || "default"}___`;
|
|
804
|
+
const delay = opts.throttle || 16;
|
|
805
|
+
let last = 0;
|
|
806
|
+
|
|
807
|
+
// 1、重写 emit
|
|
808
|
+
const rawEmit = bus.emit;
|
|
809
|
+
bus.emit = function (name, data, fnThis) {
|
|
810
|
+
rawEmit.call(bus, name, data, fnThis); // 本地先执行
|
|
811
|
+
const now = Date.now();
|
|
812
|
+
if (now - last < delay) return;
|
|
813
|
+
last = now;
|
|
814
|
+
const key = ns + name;
|
|
815
|
+
try {
|
|
816
|
+
localStorage.setItem(key, JSON.stringify({ name, data, ts: now }));
|
|
817
|
+
localStorage.removeItem(key); // 触发 storage 事件
|
|
818
|
+
} catch (e) {}
|
|
819
|
+
};
|
|
820
|
+
|
|
821
|
+
// 2、监听其他页广播
|
|
822
|
+
function onStorageHandler(e) {
|
|
823
|
+
if (!e.key || !e.key.startsWith(ns)) return;
|
|
824
|
+
let payload;
|
|
825
|
+
try {
|
|
826
|
+
payload = JSON.parse(e.newValue || "{}");
|
|
827
|
+
} catch {
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
if (!payload.ts || payload.ts <= last) return;
|
|
831
|
+
rawEmit.call(bus, e.key.slice(ns.length), payload.data); // 仅本地
|
|
832
|
+
}
|
|
833
|
+
addEventListener("storage", onStorageHandler);
|
|
834
|
+
|
|
835
|
+
// 3、保存卸载器
|
|
836
|
+
bus._uninstallCrossPage = () => {
|
|
837
|
+
removeEventListener("storage", onStorageHandler);
|
|
838
|
+
bus.emit = rawEmit;
|
|
839
|
+
INSTALLED.delete(bus);
|
|
840
|
+
};
|
|
841
|
+
},
|
|
842
|
+
|
|
843
|
+
/**
|
|
844
|
+
* 卸载插件,恢复原始 emit 并停止监听。
|
|
845
|
+
* @param {MyEvent} bus - 事件总线实例
|
|
846
|
+
*/
|
|
847
|
+
uninstall(bus) {
|
|
848
|
+
if (typeof bus._uninstallCrossPage === "function") bus._uninstallCrossPage();
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
})();
|
|
852
|
+
|
|
853
|
+
/**
|
|
854
|
+
* 生成 RFC4122 版本 4 的 GUID/UUID。
|
|
855
|
+
* 收集来源:《基于mvc的javascript web富应用开发》 书中介绍是Robert Kieffer写的,还留了网址 http://goo.gl/0b0hu ,但实际访问不了。
|
|
856
|
+
* 格式:`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`
|
|
857
|
+
*
|
|
858
|
+
* @returns {string} 36 位大写 GUID
|
|
859
|
+
*
|
|
860
|
+
* @example
|
|
861
|
+
* // A2E0F340-6C3B-4D7F-B8C1-1E4F6A8B9C0D
|
|
862
|
+
* console.log(getGUID())
|
|
863
|
+
*/
|
|
864
|
+
function getGUID() {
|
|
865
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
866
|
+
let r = (Math.random() * 16) | 0,
|
|
867
|
+
v = c == "x" ? r : (r & 0x3) | 0x8;
|
|
868
|
+
return v.toString(16).toUpperCase();
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* 分布式短 ID 生成器。
|
|
874
|
+
* 格式:`${timestamp}${flag}${serial}`,其中:
|
|
875
|
+
* - timestamp:毫秒级时间戳
|
|
876
|
+
* - flag:客户端标识串(自定义)
|
|
877
|
+
* - serial:同一毫秒内的序号,左补零到固定长度
|
|
878
|
+
*/
|
|
879
|
+
class MyId {
|
|
880
|
+
#ts = Date.now(); // 时间戳
|
|
881
|
+
#sn = 0; // 序号(保证同一客户端之间的唯一项)
|
|
882
|
+
#flag = ""; // 客户端标识(保证不同客户端之间的唯一项)
|
|
883
|
+
#len = 5; // 序号位长度(我的电脑测试,同一时间戳内可以for循环执行了1000次左右,没有一次超过3k,所以5位应该够用了)
|
|
884
|
+
// 测试代码
|
|
885
|
+
// let obj = {[Date.now()]:[]}; try { for (let i = 0; i < 100000; i++) { obj[Date.now()].push(i); } } catch { console.log(obj[Object.getOwnPropertyNames(obj)[0]].length); }
|
|
886
|
+
|
|
887
|
+
/**
|
|
888
|
+
* @param {object} [option]
|
|
889
|
+
* @param {string} [option.flag] - 客户端标识,默认空串
|
|
890
|
+
* @param {number} [option.len=5] - 序号位长度(位数),安全范围 ≥0
|
|
891
|
+
*/
|
|
892
|
+
constructor(option = {}) {
|
|
893
|
+
if (option) {
|
|
894
|
+
if (typeof option.flag === "string") {
|
|
895
|
+
this.#flag = option.flag;
|
|
896
|
+
}
|
|
897
|
+
if (Number.isSafeInteger(option.len) && len >= 0) {
|
|
898
|
+
this.#len = option.len;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/**
|
|
904
|
+
* 生成下一个全局唯一字符串 ID。
|
|
905
|
+
* 同一毫秒序号自动递增;序号溢出时会在控制台警告。
|
|
906
|
+
* @returns {string}
|
|
907
|
+
*/
|
|
908
|
+
nextId() {
|
|
909
|
+
let ts = Date.now();
|
|
910
|
+
if (ts === this.#ts) {
|
|
911
|
+
this.#sn++;
|
|
912
|
+
if (this.#sn >= 10 ** this.#len) {
|
|
913
|
+
console.log("长度不够用了!!!");
|
|
914
|
+
}
|
|
915
|
+
} else {
|
|
916
|
+
this.#sn = 0;
|
|
917
|
+
this.#ts = ts;
|
|
918
|
+
}
|
|
919
|
+
return ts.toString() + this.#flag + this.#sn.toString().padStart(this.#len, "0");
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
/**
|
|
924
|
+
* 基于 `setTimeout` 的“间隔循环”定时器。
|
|
925
|
+
* 每次任务执行完成后才计算下一次间隔,避免任务堆积。
|
|
926
|
+
*/
|
|
927
|
+
class IntervalTimer {
|
|
928
|
+
|
|
929
|
+
/**
|
|
930
|
+
* 创建定时器实例。
|
|
931
|
+
* @param {() => void} fn - 每次间隔要执行的业务函数
|
|
932
|
+
* @param {number} [ms=1000] - 间隔时间(毫秒)
|
|
933
|
+
* @throws {TypeError} 当 `fn` 不是函数时抛出
|
|
934
|
+
*/
|
|
935
|
+
constructor(fn, ms = 1000) {
|
|
936
|
+
if (typeof fn !== "function") {
|
|
937
|
+
throw new TypeError("IntervalTimer: 必须传入一个函数");
|
|
938
|
+
}
|
|
939
|
+
this._fn = fn;
|
|
940
|
+
this._ms = ms;
|
|
941
|
+
this._timerId = null;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* 启动定时器;若已启动则先停止再重新启动。
|
|
946
|
+
* 首次执行会立即触发。
|
|
947
|
+
*/
|
|
948
|
+
start() {
|
|
949
|
+
this.stop();
|
|
950
|
+
const loop = () => {
|
|
951
|
+
this._fn(); // 执行业务
|
|
952
|
+
this._timerId = setTimeout(loop, this._ms);
|
|
953
|
+
};
|
|
954
|
+
loop(); // 立即执行第一次
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* 停止定时器。
|
|
959
|
+
*/
|
|
960
|
+
stop() {
|
|
961
|
+
if (this._timerId !== null) {
|
|
962
|
+
clearTimeout(this._timerId);
|
|
963
|
+
this._timerId = null;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
/**
|
|
968
|
+
* 查询定时器是否正在运行。
|
|
969
|
+
* @returns {boolean}
|
|
970
|
+
*/
|
|
971
|
+
isRunning() {
|
|
972
|
+
return this._timerId !== null;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/**
|
|
977
|
+
* 把嵌套树拍平成 `{ [id]: node }` 映射,同时把原 `children` 置为 `null`。
|
|
978
|
+
*
|
|
979
|
+
* @template T extends Record<PropertyKey, any>
|
|
980
|
+
* @param {T[]} data - 嵌套树森林
|
|
981
|
+
* @param {string} [idKey='id'] - 主键字段
|
|
982
|
+
* @param {string} [childrenKey='children'] - 子节点字段
|
|
983
|
+
* @returns {Record<string, T & { [k in typeof childrenKey]: null }>} id→节点的映射表
|
|
984
|
+
*/
|
|
985
|
+
function nestedTree2IdMap(data, idKey = "id", childrenKey = "children") {
|
|
986
|
+
const retObj = {};
|
|
987
|
+
function fn(nodes) {
|
|
988
|
+
if (Array.isArray(nodes) && nodes.length > 0) {
|
|
989
|
+
nodes.forEach((node) => {
|
|
990
|
+
retObj[node[idKey]] = { ...node };
|
|
991
|
+
retObj[node[idKey]][childrenKey] = null;
|
|
992
|
+
|
|
993
|
+
fn(node[childrenKey]);
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
fn(data);
|
|
998
|
+
return retObj;
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/**
|
|
1002
|
+
* 把**已包含完整父子关系**的扁平节点列表还原成嵌套树(森林)。
|
|
1003
|
+
*
|
|
1004
|
+
* @template T extends Record<PropertyKey, any>
|
|
1005
|
+
* @param {T[]} nodes - 扁平节点列表(必须包含 id / parentId)
|
|
1006
|
+
* @param {number | string} [parentId=0] - 根节点标识值
|
|
1007
|
+
* @param {Object} [opts] - 字段映射配置
|
|
1008
|
+
* @param {string} [opts.idKey='id'] - 节点主键
|
|
1009
|
+
* @param {string} [opts.parentKey='parentId'] - 父节点外键
|
|
1010
|
+
* @param {string} [opts.childrenKey='children'] - 存放子节点的字段
|
|
1011
|
+
* @returns {(T & { [k in typeof childrenKey]: T[] })[]} 嵌套树森林
|
|
1012
|
+
*/
|
|
1013
|
+
function flatCompleteTree2NestedTree(nodes, parentId = 0, { idKey = "id", parentKey = "parentId", childrenKey = "children" } = {}) {
|
|
1014
|
+
const map = new Map(); // id -> node
|
|
1015
|
+
const items = []; // 多根森林
|
|
1016
|
+
|
|
1017
|
+
// 1. 初始化:保证每个节点都有 children,并存入 map
|
|
1018
|
+
for (const item of nodes) {
|
|
1019
|
+
const node = { ...item, [childrenKey]: [] };
|
|
1020
|
+
map.set(item[idKey], node);
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
// 2. 建立父子关系
|
|
1024
|
+
for (const item of nodes) {
|
|
1025
|
+
const node = map.get(item[idKey]);
|
|
1026
|
+
const parentIdVal = item[parentKey];
|
|
1027
|
+
|
|
1028
|
+
if (parentIdVal === parentId) {
|
|
1029
|
+
// 根层
|
|
1030
|
+
items.push(node);
|
|
1031
|
+
} else {
|
|
1032
|
+
// 非根层:找到父节点,把自己挂上去
|
|
1033
|
+
const parent = map.get(parentIdVal);
|
|
1034
|
+
if (parent) parent[childrenKey].push(node);
|
|
1035
|
+
// 如果 parent 不存在,说明数据不完整,可自定义处理
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
return items;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
/**
|
|
1043
|
+
* 在嵌套树中按 `id` 递归查找节点,并返回其指定属性值。
|
|
1044
|
+
*
|
|
1045
|
+
* @template T extends Record<PropertyKey, any>
|
|
1046
|
+
* @param {string | number} id - 要查找的 id
|
|
1047
|
+
* @param {T[]} arr - 嵌套树森林
|
|
1048
|
+
* @param {string} [resultKey='name'] - 需要返回的字段
|
|
1049
|
+
* @param {string} [idKey='id'] - 主键字段
|
|
1050
|
+
* @param {string} [childrenKey='children'] - 子节点字段
|
|
1051
|
+
* @returns {any} 找到的值;未找到返回 `undefined`
|
|
1052
|
+
*/
|
|
1053
|
+
const findObjAttrValueById = function findObjAttrValueByIdFn(id, arr, resultKey = "name", idKey = "id", childrenKey = "children") {
|
|
1054
|
+
if (Array.isArray(arr) && arr.length > 0) {
|
|
1055
|
+
for (let i = 0; i < arr.length; i++) {
|
|
1056
|
+
const item = arr[i];
|
|
1057
|
+
if (item[idKey]?.toString() === id?.toString()) {
|
|
1058
|
+
return item[resultKey];
|
|
1059
|
+
} else if (Array.isArray(item[childrenKey]) && item[childrenKey].length > 0) {
|
|
1060
|
+
const result = findObjAttrValueByIdFn(id, item[childrenKey], resultKey, idKey, childrenKey);
|
|
1061
|
+
if (result) {
|
|
1062
|
+
return result;
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
};
|
|
1068
|
+
|
|
1069
|
+
export { IntervalTimer, MyEvent, MyEvent_CrossPagePlugin, MyId, assignExisting, calcTimeDifference, debounce, deepCloneByJSON, downloadByBlob, downloadByData, downloadByUrl, downloadExcel, downloadJSON, findObjAttrValueById, flatCompleteTree2NestedTree, formatDuration, formatDurationMaxDay, formatDurationMaxHour, getAllSearchParams, getDataType, getFunctionArgNames, getGUID, getSearchParam, getViewportSize, isBlob, isDate, isFunction, isNonEmptyString, isPlainObject, isPromise, moveItem, nestedTree2IdMap, randomDateInRange, randomEnLetter, randomHan, randomHanOrEn, randomIntInRange, readBlobAsText, shuffle, throttle, toDate };
|
|
1070
|
+
//# sourceMappingURL=a2bei4.utils.esm.js.map
|