nhanh-pure-function 1.3.3 → 1.3.5

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.
@@ -1,480 +1,480 @@
1
- /**
2
- * 非null | undefined判断
3
- * @param value any
4
- * @returns boolean
5
- */
6
- export function _NotNull(value) {
7
- return value !== null && value !== undefined;
8
- }
9
-
10
- /**
11
- * 是正常对象吗
12
- * @param {} value
13
- * @returns boolean
14
- */
15
- export function _IsObject(value) {
16
- return !(value === null || typeof value !== "object" || Array.isArray(value));
17
- }
18
-
19
- /**
20
- * 寻找空闲时机执行传入方法
21
- * @param callback 需执行的方法
22
- */
23
- export function _ExecuteWhenIdle(callback) {
24
- if (typeof callback !== "function")
25
- return console.error("非函数:", callback);
26
- const loop = function (deadline) {
27
- if (deadline.didTimeout || deadline.timeRemaining() <= 0)
28
- requestIdleCallback(loop);
29
- else callback();
30
- };
31
- requestIdleCallback(loop);
32
- }
33
-
34
- /**
35
- * 等待条件满足
36
- * @param conditionChecker 条件检查器
37
- * @param timeoutMillis 超时毫秒数
38
- * @returns Promise<unknown>
39
- */
40
- export function _WaitForCondition(conditionChecker, timeoutMillis) {
41
- const startTime = new Date() - 0;
42
- return new Promise((resolve, reject) => {
43
- const checkCondition = () => {
44
- const nowTime = new Date() - 0;
45
- if (nowTime - startTime >= timeoutMillis) return reject("超时");
46
- if (conditionChecker()) return resolve("完成");
47
- requestIdleCallback(checkCondition);
48
- };
49
- checkCondition();
50
- });
51
- }
52
-
53
- /**
54
- * 排除子串
55
- * @param inputString 需裁剪字符串
56
- * @param substringToDelete 被裁减字符串
57
- * @param delimiter 分隔符
58
- * @returns 裁减后的字符串
59
- */
60
- export function _ExcludeSubstring(
61
- inputString,
62
- substringToDelete,
63
- delimiter = ","
64
- ) {
65
- const regex = new RegExp(
66
- `(^|${delimiter})${substringToDelete}(${delimiter}|$)`,
67
- "g"
68
- );
69
- return inputString.replace(regex, function ($0, $1, $2) {
70
- return $1 === $2 ? delimiter : "";
71
- });
72
- }
73
-
74
- /**
75
- * 首字母大写
76
- * @param str
77
- * @returns string
78
- */
79
- export function _CapitalizeFirstLetter(string) {
80
- return string.charAt(0).toUpperCase() + string.slice(1);
81
- }
82
-
83
- /**
84
- * 合并对象 注意: 本函数会直接操作 A
85
- * @param {Object | Array} A
86
- * @param {Object | Array} B
87
- * @returns A&B || B
88
- */
89
- export function _MergeObjects(A, B, visitedObjects = []) {
90
- const getType = (v) => (Array.isArray(v) ? "array" : typeof v);
91
- const TA = getType(A);
92
- const TB = getType(B);
93
-
94
- if (TA != TB) return B;
95
- if (visitedObjects.some((item) => item == B)) return B;
96
-
97
- if (TA == "object") {
98
- visitedObjects.push(A, B);
99
- for (const key in B) {
100
- if (Object.prototype.hasOwnProperty.call(B, key)) {
101
- const BC = B[key];
102
- const AC = A[key];
103
- const fianlValue = _MergeObjects(AC, BC, visitedObjects);
104
- A[key] = fianlValue;
105
- }
106
- }
107
- return A;
108
- } else if (TA == "array") {
109
- visitedObjects.push(A, B);
110
- B.forEach((item, index) => {
111
- const BC = item;
112
- const AC = A[index];
113
- const fianlValue = _MergeObjects(AC, BC, visitedObjects);
114
- A[index] = fianlValue;
115
- });
116
- return A;
117
- } else return B;
118
- }
119
-
120
- /**
121
- * 时间戳转换字符串
122
- * @param {Number | Date} time 时间戳或Date对象
123
- * @param {String} template 完整模板 --> yyyy MM DD hh mm ss ms
124
- * @param {Boolean} pad 补0
125
- */
126
- export function _TimeTransition(time, template, pad = true) {
127
- try {
128
- time = new Date(time);
129
- } catch (error) {
130
- console.error(error);
131
- return "";
132
- }
133
- const dictionary = {
134
- yyyy: "getFullYear",
135
- MM: "getMonth",
136
- DD: "getDate",
137
- hh: "getHours",
138
- mm: "getMinutes",
139
- ss: "getSeconds",
140
- ms: (num) => +num % 1000,
141
- };
142
- for (const key in dictionary) {
143
- if (Object.hasOwnProperty.call(dictionary, key)) {
144
- if (new RegExp(key).test(template)) {
145
- let value,
146
- fun = dictionary[key];
147
-
148
- if (typeof fun == "function") value = fun(time);
149
- else value = time[fun]();
150
-
151
- if (key == "MM") value++;
152
-
153
- if (pad) value = String(value).padStart(2, "0");
154
-
155
- template = template.replace(key, value);
156
- }
157
- }
158
- }
159
- return template;
160
- }
161
-
162
- /**
163
- * 读取文件
164
- * @param src 文件地址
165
- * @returns 文件的字符串内容
166
- */
167
- export function _ReadFile(src) {
168
- return new Promise((resolve, reject) => {
169
- fetch(src)
170
- .then((response) => resolve(response.text()))
171
- .catch((error) => {
172
- console.error("Error fetching :", error);
173
- reject(error);
174
- });
175
- });
176
- }
177
-
178
- /**
179
- * 下载文件
180
- * @param {文件路径} href
181
- * @param {导出文件名} download
182
- */
183
- export function _DownloadFile(href, fileName) {
184
- const a = document.createElement("a");
185
- a.href = href;
186
- if (fileName) a.download = fileName;
187
- a.style.display = "none";
188
- document.body.appendChild(a);
189
- a.click();
190
- a.remove();
191
- }
192
-
193
- /**
194
- * 获取帧率
195
- * @param {(fps , frameTime)=>void} callback callback( 帧率 , 每帧时间 )
196
- * @param {Number} referenceNode 参考节点数量
197
- */
198
- export function _GetFrameRate(callback, referenceNode = 10) {
199
- let t,
200
- l = referenceNode;
201
- function loop() {
202
- if (l > 0) {
203
- l--;
204
- requestAnimationFrame(loop);
205
- } else {
206
- const time = new Date() - t;
207
- const frameTime = time / referenceNode;
208
- const fps = 1000 / frameTime;
209
- callback(Number(fps.toFixed(2)), Number(frameTime.toFixed(2)));
210
- }
211
- }
212
- requestAnimationFrame(() => {
213
- t = new Date() - 0;
214
- loop();
215
- });
216
- }
217
-
218
- /**
219
- * 单位转换 12** -> **px
220
- * @param {string} width
221
- * @returns 对应的单位为px的宽
222
- */
223
- export function _GetOtherSizeInPixels(width) {
224
- if (/px/.test(width)) return width;
225
- const dom = document.createElement("div");
226
- dom.style.width = width;
227
- document.body.appendChild(dom);
228
- width = parseFloat(window.getComputedStyle(dom).width);
229
- document.body.removeChild(dom);
230
- return width;
231
- }
232
-
233
- /**
234
- * 驼峰命名
235
- * @param {字符串} str
236
- * @param {是否删除分割字符} isRemoveDelimiter
237
- * @returns 'wq1wqw-qw2qw' -> 'wq1Wqw-Qw2Qw' / 'wqWqwQwQw'
238
- */
239
- export function _ConvertToCamelCase(str, isRemoveDelimiter) {
240
- str = str.replace(/([^a-zA-Z][a-z])/g, (match) => match.toUpperCase());
241
- if (isRemoveDelimiter) return str.replace(/[^a-zA-Z]+/g, "");
242
- return str;
243
- }
244
-
245
- /**
246
- * 创建文件并下载
247
- * @param {BlobPart[]} content 文件内容
248
- * @param {string} fileName 文件名称
249
- * @param {BlobPropertyBag} options Blob 配置
250
- */
251
- export function _CreateAndDownloadFile(content, fileName, options) {
252
- if (!options) {
253
- let type = fileName.replace(/^[^.]+./, "");
254
- type = type == fileName ? "text/plain" : "application/" + type;
255
- options = { type };
256
- }
257
- const bolb = new Blob(content, options);
258
- // 创建一个 URL,该 URL 可以用于在浏览器中引用 Blob 对象(例如,在 <a> 标签的 href 属性中)
259
- const url = URL.createObjectURL(bolb);
260
- // 你可以创建一个链接来下载这个 Blob 对象
261
- const downloadLink = document.createElement("a");
262
- downloadLink.href = url;
263
- downloadLink.download = fileName; // 设置下载文件的名称
264
- document.body.appendChild(downloadLink); // 添加到文档中
265
- downloadLink.click(); // 模拟点击以开始下载
266
- document.body.removeChild(downloadLink); // 然后从文档中移除
267
- // 最后,别忘了撤销 Blob 对象的 URL,以释放资源
268
- URL.revokeObjectURL(url);
269
- }
270
-
271
- /**
272
- * 获取url参数
273
- * @param {string} url
274
- * @returns {Object}
275
- */
276
- export function _GetQueryParams(url) {
277
- const queryString = url.split("?")[1] || "";
278
- const params = new URLSearchParams(queryString);
279
- const result = {};
280
-
281
- params.forEach((value, key) => {
282
- result[key] = value;
283
- });
284
-
285
- return result;
286
- }
287
-
288
- /**
289
- * 生成uuid
290
- * @returns {string}
291
- */
292
- export function _GenerateUUID() {
293
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
294
- const r = (Math.random() * 16) | 0; // 随机生成一个0到15的数
295
- const v = c === "x" ? r : (r & 0x3) | 0x8; // 对于'y'位, v = (r & 0x3 | 0x8) 确保变体正确
296
- return v.toString(16); // 将数字转换为16进制
297
- });
298
- }
299
-
300
- /**
301
- * 防抖
302
- * @param {Function} fn
303
- * @param {number} delay
304
- * @returns {Function}
305
- */
306
- export function _Debounce(fn, delay) {
307
- let timeoutId;
308
- return function (...args) {
309
- clearTimeout(timeoutId);
310
- timeoutId = setTimeout(() => fn.apply(this, args), delay);
311
- };
312
- }
313
-
314
- /**
315
- * 节流
316
- * @param {Function} fn
317
- * @param {number} delay
318
- * @returns {Function}
319
- */
320
- export function _Throttle(fn, delay) {
321
- let timer;
322
- return function (...args) {
323
- if (!timer) {
324
- timer = setTimeout(() => {
325
- fn.apply(this, args);
326
- timer = null;
327
- }, delay);
328
- }
329
- };
330
- }
331
-
332
- /**
333
- * 数据类型
334
- * @param {any} value
335
- * @returns string
336
- */
337
- export function _DataType(value) {
338
- if (Array.isArray(value)) return "array";
339
- if (value === null) return "null";
340
- return typeof value;
341
- }
342
-
343
- /**
344
- * 复制到剪贴板
345
- * @param {string} text
346
- */
347
- export function _CopyToClipboard(text) {
348
- const handleSuccess = () => Promise.resolve();
349
- const handleError = (error) => {
350
- console.error(error);
351
- return Promise.reject(error);
352
- };
353
-
354
- /** 最新方式 */
355
- function writeText() {
356
- return navigator.clipboard
357
- .writeText(text)
358
- .then(handleSuccess)
359
- .catch(handleError);
360
- }
361
- /** 旧方式 - createRange */
362
- function createRange() {
363
- const div = document.createElement("div");
364
- div.innerText = text;
365
- document.body.appendChild(div);
366
-
367
- const range = document.createRange();
368
- range.selectNodeContents(div);
369
- const selection = window.getSelection();
370
-
371
- let isFinished = false;
372
- if (selection) {
373
- selection.removeAllRanges();
374
- selection.addRange(range);
375
-
376
- isFinished = document.execCommand("copy");
377
- }
378
- document.body.removeChild(div);
379
- return isFinished ? Promise.resolve() : Promise.reject();
380
- }
381
- /** 旧方式 - execCommand */
382
- function execCommand() {
383
- const textarea = document.createElement("textarea");
384
- textarea.value = text;
385
- document.body.appendChild(textarea);
386
-
387
- textarea.select();
388
- textarea.setSelectionRange(0, text.length); // 对于移动设备
389
-
390
- let isFinished = false;
391
-
392
- /** aria-hidden 及 tabindex 可能会影响聚焦元素 */
393
- if (document.activeElement === textarea)
394
- isFinished = document.execCommand("Copy", true);
395
-
396
- document.body.removeChild(textarea);
397
- return isFinished ? Promise.resolve() : Promise.reject();
398
- }
399
-
400
- function old() {
401
- return createRange()
402
- .then(handleSuccess)
403
- .catch(() => {
404
- execCommand()
405
- .then(handleSuccess)
406
- .catch(() => handleError("复制方式尽皆失效"));
407
- });
408
- }
409
-
410
- if (navigator.clipboard) return writeText().catch(old);
411
- return old();
412
- }
413
-
414
- /**
415
- * 格式化文件大小
416
- * @param {number} size
417
- * @returns string
418
- */
419
- export function _FormatFileSize(size) {
420
- const units = ["B", "KB", "MB", "GB", "TB", "PB"];
421
- let unitIndex = 0;
422
- while (size > 1024) {
423
- size /= 1024;
424
- unitIndex++;
425
- }
426
- return `${Math.round(size * 100) / 100} ${units[unitIndex]}`;
427
- }
428
-
429
- /**
430
- * 根据路径初始化目标对象
431
- * 如果路径中某个属性不存在,则会创建该属性及其所有父属性
432
- * 最终返回路径的最后一个属性对应的值或undefined(如果路径不存在)
433
- *
434
- * @param {Object} model - 要初始化的模型对象
435
- * @param {string} path - 属性路径,使用英文句点分隔
436
- * @returns {any} 路径的最后一个属性对应的值或undefined
437
- */
438
- export function _InitTargetByPath(model, path) {
439
- const arr = path.split(".");
440
- return arr.reduce((prev, curr, index) => {
441
- if (!(curr in prev)) {
442
- if (index === arr.length - 1) prev[curr] = undefined;
443
- else prev[curr] = {};
444
- }
445
- return prev[curr];
446
- }, model);
447
- }
448
- /**
449
- * 根据路径获取目标对象
450
- * 该函数用于在给定的模型中,通过路径字符串来获取深层嵌套的目标对象如果路径中的某一部分不存在,则会创建一个新的对象(除非已经是路径的最后一部分)
451
- *
452
- * @param {Object} model - 包含要查询的数据的模型对象
453
- * @param {string} path - 用点分隔的路径字符串,表示要访问的对象属性路径
454
- * @returns {Object|undefined} - 返回目标对象,如果路径不存在则返回undefined
455
- */
456
- export function _GetTargetByPath(model, path) {
457
- const arr = path.split(".");
458
- return arr.reduce((prev, curr, index) => {
459
- if (prev.hasOwnProperty(curr)) return prev[curr];
460
- return (prev[curr] = index == arr.length - 1 ? undefined : {});
461
- }, model);
462
- }
463
- /**
464
- * 根据路径更新目标值
465
- *
466
- * 该函数通过一个点分隔的路径来更新一个对象中的嵌套属性值
467
- * 它使用了reduce方法来遍历路径数组,并在路径的终点设置新的值
468
- *
469
- * @param {Object} model - 包含要更新数据的模型对象
470
- * @param {string} path - 点分隔的字符串路径,指示如何到达目标属性
471
- * @param {*} value - 要设置的新值
472
- * @returns {*} - 返回更新后的模型对象中的值
473
- */
474
- export function _UpdateTargetByPath(model, path, value) {
475
- const arr = path.split(".");
476
- return arr.reduce((prev, curr, index) => {
477
- if (index === arr.length - 1) prev[curr] = value;
478
- return prev[curr];
479
- }, model);
480
- }
1
+ /**
2
+ * 非null | undefined判断
3
+ * @param value any
4
+ * @returns boolean
5
+ */
6
+ export function _NotNull(value) {
7
+ return value !== null && value !== undefined;
8
+ }
9
+
10
+ /**
11
+ * 是正常对象吗
12
+ * @param {} value
13
+ * @returns boolean
14
+ */
15
+ export function _IsObject(value) {
16
+ return !(value === null || typeof value !== "object" || Array.isArray(value));
17
+ }
18
+
19
+ /**
20
+ * 寻找空闲时机执行传入方法
21
+ * @param callback 需执行的方法
22
+ */
23
+ export function _ExecuteWhenIdle(callback) {
24
+ if (typeof callback !== "function")
25
+ return console.error("非函数:", callback);
26
+ const loop = function (deadline) {
27
+ if (deadline.didTimeout || deadline.timeRemaining() <= 0)
28
+ requestIdleCallback(loop);
29
+ else callback();
30
+ };
31
+ requestIdleCallback(loop);
32
+ }
33
+
34
+ /**
35
+ * 等待条件满足
36
+ * @param conditionChecker 条件检查器
37
+ * @param timeoutMillis 超时毫秒数
38
+ * @returns Promise<unknown>
39
+ */
40
+ export function _WaitForCondition(conditionChecker, timeoutMillis) {
41
+ const startTime = new Date() - 0;
42
+ return new Promise((resolve, reject) => {
43
+ const checkCondition = () => {
44
+ const nowTime = new Date() - 0;
45
+ if (nowTime - startTime >= timeoutMillis) return reject("超时");
46
+ if (conditionChecker()) return resolve("完成");
47
+ requestIdleCallback(checkCondition);
48
+ };
49
+ checkCondition();
50
+ });
51
+ }
52
+
53
+ /**
54
+ * 排除子串
55
+ * @param inputString 需裁剪字符串
56
+ * @param substringToDelete 被裁减字符串
57
+ * @param delimiter 分隔符
58
+ * @returns 裁减后的字符串
59
+ */
60
+ export function _ExcludeSubstring(
61
+ inputString,
62
+ substringToDelete,
63
+ delimiter = ","
64
+ ) {
65
+ const regex = new RegExp(
66
+ `(^|${delimiter})${substringToDelete}(${delimiter}|$)`,
67
+ "g"
68
+ );
69
+ return inputString.replace(regex, function ($0, $1, $2) {
70
+ return $1 === $2 ? delimiter : "";
71
+ });
72
+ }
73
+
74
+ /**
75
+ * 首字母大写
76
+ * @param str
77
+ * @returns string
78
+ */
79
+ export function _CapitalizeFirstLetter(string) {
80
+ return string.charAt(0).toUpperCase() + string.slice(1);
81
+ }
82
+
83
+ /**
84
+ * 合并对象 注意: 本函数会直接操作 A
85
+ * @param {Object | Array} A
86
+ * @param {Object | Array} B
87
+ * @returns A&B || B
88
+ */
89
+ export function _MergeObjects(A, B, visitedObjects = []) {
90
+ const getType = (v) => (Array.isArray(v) ? "array" : typeof v);
91
+ const TA = getType(A);
92
+ const TB = getType(B);
93
+
94
+ if (TA != TB) return B;
95
+ if (visitedObjects.some((item) => item == B)) return B;
96
+
97
+ if (TA == "object") {
98
+ visitedObjects.push(A, B);
99
+ for (const key in B) {
100
+ if (Object.prototype.hasOwnProperty.call(B, key)) {
101
+ const BC = B[key];
102
+ const AC = A[key];
103
+ const fianlValue = _MergeObjects(AC, BC, visitedObjects);
104
+ A[key] = fianlValue;
105
+ }
106
+ }
107
+ return A;
108
+ } else if (TA == "array") {
109
+ visitedObjects.push(A, B);
110
+ B.forEach((item, index) => {
111
+ const BC = item;
112
+ const AC = A[index];
113
+ const fianlValue = _MergeObjects(AC, BC, visitedObjects);
114
+ A[index] = fianlValue;
115
+ });
116
+ return A;
117
+ } else return B;
118
+ }
119
+
120
+ /**
121
+ * 时间戳转换字符串
122
+ * @param {Number | Date} time 时间戳或Date对象
123
+ * @param {String} template 完整模板 --> yyyy MM DD hh mm ss ms
124
+ * @param {Boolean} pad 补0
125
+ */
126
+ export function _TimeTransition(time, template, pad = true) {
127
+ try {
128
+ time = new Date(time);
129
+ } catch (error) {
130
+ console.error(error);
131
+ return "";
132
+ }
133
+ const dictionary = {
134
+ yyyy: "getFullYear",
135
+ MM: "getMonth",
136
+ DD: "getDate",
137
+ hh: "getHours",
138
+ mm: "getMinutes",
139
+ ss: "getSeconds",
140
+ ms: (num) => +num % 1000,
141
+ };
142
+ for (const key in dictionary) {
143
+ if (Object.hasOwnProperty.call(dictionary, key)) {
144
+ if (new RegExp(key).test(template)) {
145
+ let value,
146
+ fun = dictionary[key];
147
+
148
+ if (typeof fun == "function") value = fun(time);
149
+ else value = time[fun]();
150
+
151
+ if (key == "MM") value++;
152
+
153
+ if (pad) value = String(value).padStart(2, "0");
154
+
155
+ template = template.replace(key, value);
156
+ }
157
+ }
158
+ }
159
+ return template;
160
+ }
161
+
162
+ /**
163
+ * 读取文件
164
+ * @param src 文件地址
165
+ * @returns 文件的字符串内容
166
+ */
167
+ export function _ReadFile(src) {
168
+ return new Promise((resolve, reject) => {
169
+ fetch(src)
170
+ .then((response) => resolve(response.text()))
171
+ .catch((error) => {
172
+ console.error("Error fetching :", error);
173
+ reject(error);
174
+ });
175
+ });
176
+ }
177
+
178
+ /**
179
+ * 下载文件
180
+ * @param {文件路径} href
181
+ * @param {导出文件名} download
182
+ */
183
+ export function _DownloadFile(href, fileName) {
184
+ const a = document.createElement("a");
185
+ a.href = href;
186
+ if (fileName) a.download = fileName;
187
+ a.style.display = "none";
188
+ document.body.appendChild(a);
189
+ a.click();
190
+ a.remove();
191
+ }
192
+
193
+ /**
194
+ * 获取帧率
195
+ * @param {(fps , frameTime)=>void} callback callback( 帧率 , 每帧时间 )
196
+ * @param {Number} referenceNode 参考节点数量
197
+ */
198
+ export function _GetFrameRate(callback, referenceNode = 10) {
199
+ let t,
200
+ l = referenceNode;
201
+ function loop() {
202
+ if (l > 0) {
203
+ l--;
204
+ requestAnimationFrame(loop);
205
+ } else {
206
+ const time = new Date() - t;
207
+ const frameTime = time / referenceNode;
208
+ const fps = 1000 / frameTime;
209
+ callback(Number(fps.toFixed(2)), Number(frameTime.toFixed(2)));
210
+ }
211
+ }
212
+ requestAnimationFrame(() => {
213
+ t = new Date() - 0;
214
+ loop();
215
+ });
216
+ }
217
+
218
+ /**
219
+ * 单位转换 12** -> **px
220
+ * @param {string} width
221
+ * @returns 对应的单位为px的宽
222
+ */
223
+ export function _GetOtherSizeInPixels(width) {
224
+ if (/px/.test(width)) return width;
225
+ const dom = document.createElement("div");
226
+ dom.style.width = width;
227
+ document.body.appendChild(dom);
228
+ width = parseFloat(window.getComputedStyle(dom).width);
229
+ document.body.removeChild(dom);
230
+ return width;
231
+ }
232
+
233
+ /**
234
+ * 驼峰命名
235
+ * @param {字符串} str
236
+ * @param {是否删除分割字符} isRemoveDelimiter
237
+ * @returns 'wq1wqw-qw2qw' -> 'wq1Wqw-Qw2Qw' / 'wqWqwQwQw'
238
+ */
239
+ export function _ConvertToCamelCase(str, isRemoveDelimiter) {
240
+ str = str.replace(/([^a-zA-Z][a-z])/g, (match) => match.toUpperCase());
241
+ if (isRemoveDelimiter) return str.replace(/[^a-zA-Z]+/g, "");
242
+ return str;
243
+ }
244
+
245
+ /**
246
+ * 创建文件并下载
247
+ * @param {BlobPart[]} content 文件内容
248
+ * @param {string} fileName 文件名称
249
+ * @param {BlobPropertyBag} options Blob 配置
250
+ */
251
+ export function _CreateAndDownloadFile(content, fileName, options) {
252
+ if (!options) {
253
+ let type = fileName.replace(/^[^.]+./, "");
254
+ type = type == fileName ? "text/plain" : "application/" + type;
255
+ options = { type };
256
+ }
257
+ const bolb = new Blob(content, options);
258
+ // 创建一个 URL,该 URL 可以用于在浏览器中引用 Blob 对象(例如,在 <a> 标签的 href 属性中)
259
+ const url = URL.createObjectURL(bolb);
260
+ // 你可以创建一个链接来下载这个 Blob 对象
261
+ const downloadLink = document.createElement("a");
262
+ downloadLink.href = url;
263
+ downloadLink.download = fileName; // 设置下载文件的名称
264
+ document.body.appendChild(downloadLink); // 添加到文档中
265
+ downloadLink.click(); // 模拟点击以开始下载
266
+ document.body.removeChild(downloadLink); // 然后从文档中移除
267
+ // 最后,别忘了撤销 Blob 对象的 URL,以释放资源
268
+ URL.revokeObjectURL(url);
269
+ }
270
+
271
+ /**
272
+ * 获取url参数
273
+ * @param {string} url
274
+ * @returns {Object}
275
+ */
276
+ export function _GetQueryParams(url) {
277
+ const queryString = url.split("?")[1] || "";
278
+ const params = new URLSearchParams(queryString);
279
+ const result = {};
280
+
281
+ params.forEach((value, key) => {
282
+ result[key] = value;
283
+ });
284
+
285
+ return result;
286
+ }
287
+
288
+ /**
289
+ * 生成uuid
290
+ * @returns {string}
291
+ */
292
+ export function _GenerateUUID() {
293
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
294
+ const r = (Math.random() * 16) | 0; // 随机生成一个0到15的数
295
+ const v = c === "x" ? r : (r & 0x3) | 0x8; // 对于'y'位, v = (r & 0x3 | 0x8) 确保变体正确
296
+ return v.toString(16); // 将数字转换为16进制
297
+ });
298
+ }
299
+
300
+ /**
301
+ * 防抖
302
+ * @param {Function} fn
303
+ * @param {number} delay
304
+ * @returns {Function}
305
+ */
306
+ export function _Debounce(fn, delay) {
307
+ let timeoutId;
308
+ return function (...args) {
309
+ clearTimeout(timeoutId);
310
+ timeoutId = setTimeout(() => fn.apply(this, args), delay);
311
+ };
312
+ }
313
+
314
+ /**
315
+ * 节流
316
+ * @param {Function} fn
317
+ * @param {number} delay
318
+ * @returns {Function}
319
+ */
320
+ export function _Throttle(fn, delay) {
321
+ let timer;
322
+ return function (...args) {
323
+ if (!timer) {
324
+ timer = setTimeout(() => {
325
+ fn.apply(this, args);
326
+ timer = null;
327
+ }, delay);
328
+ }
329
+ };
330
+ }
331
+
332
+ /**
333
+ * 数据类型
334
+ * @param {any} value
335
+ * @returns string
336
+ */
337
+ export function _DataType(value) {
338
+ if (Array.isArray(value)) return "array";
339
+ if (value === null) return "null";
340
+ return typeof value;
341
+ }
342
+
343
+ /**
344
+ * 复制到剪贴板
345
+ * @param {string} text
346
+ */
347
+ export function _CopyToClipboard(text) {
348
+ const handleSuccess = () => Promise.resolve();
349
+ const handleError = (error) => {
350
+ console.error(error);
351
+ return Promise.reject(error);
352
+ };
353
+
354
+ /** 最新方式 */
355
+ function writeText() {
356
+ return navigator.clipboard
357
+ .writeText(text)
358
+ .then(handleSuccess)
359
+ .catch(handleError);
360
+ }
361
+ /** 旧方式 - createRange */
362
+ function createRange() {
363
+ const div = document.createElement("div");
364
+ div.innerText = text;
365
+ document.body.appendChild(div);
366
+
367
+ const range = document.createRange();
368
+ range.selectNodeContents(div);
369
+ const selection = window.getSelection();
370
+
371
+ let isFinished = false;
372
+ if (selection) {
373
+ selection.removeAllRanges();
374
+ selection.addRange(range);
375
+
376
+ isFinished = document.execCommand("copy");
377
+ }
378
+ document.body.removeChild(div);
379
+ return isFinished ? Promise.resolve() : Promise.reject();
380
+ }
381
+ /** 旧方式 - execCommand */
382
+ function execCommand() {
383
+ const textarea = document.createElement("textarea");
384
+ textarea.value = text;
385
+ document.body.appendChild(textarea);
386
+
387
+ textarea.select();
388
+ textarea.setSelectionRange(0, text.length); // 对于移动设备
389
+
390
+ let isFinished = false;
391
+
392
+ /** aria-hidden 及 tabindex 可能会影响聚焦元素 */
393
+ if (document.activeElement === textarea)
394
+ isFinished = document.execCommand("Copy", true);
395
+
396
+ document.body.removeChild(textarea);
397
+ return isFinished ? Promise.resolve() : Promise.reject();
398
+ }
399
+
400
+ function old() {
401
+ return createRange()
402
+ .then(handleSuccess)
403
+ .catch(() => {
404
+ execCommand()
405
+ .then(handleSuccess)
406
+ .catch(() => handleError("复制方式尽皆失效"));
407
+ });
408
+ }
409
+
410
+ if (navigator.clipboard) return writeText().catch(old);
411
+ return old();
412
+ }
413
+
414
+ /**
415
+ * 格式化文件大小
416
+ * @param {number} size
417
+ * @returns string
418
+ */
419
+ export function _FormatFileSize(size) {
420
+ const units = ["B", "KB", "MB", "GB", "TB", "PB"];
421
+ let unitIndex = 0;
422
+ while (size > 1024) {
423
+ size /= 1024;
424
+ unitIndex++;
425
+ }
426
+ return `${Math.round(size * 100) / 100} ${units[unitIndex]}`;
427
+ }
428
+
429
+ /**
430
+ * 根据路径初始化目标对象
431
+ * 如果路径中某个属性不存在,则会创建该属性及其所有父属性
432
+ * 最终返回路径的最后一个属性对应的值或undefined(如果路径不存在)
433
+ *
434
+ * @param {Object} model - 要初始化的模型对象
435
+ * @param {string} path - 属性路径,使用英文句点分隔
436
+ * @returns {any} 路径的最后一个属性对应的值或undefined
437
+ */
438
+ export function _InitTargetByPath(model, path) {
439
+ const arr = path.split(".");
440
+ return arr.reduce((prev, curr, index) => {
441
+ if (!(curr in prev)) {
442
+ if (index === arr.length - 1) prev[curr] = undefined;
443
+ else prev[curr] = {};
444
+ }
445
+ return prev[curr];
446
+ }, model);
447
+ }
448
+ /**
449
+ * 根据路径获取目标对象
450
+ * 该函数用于在给定的模型中,通过路径字符串来获取深层嵌套的目标对象如果路径中的某一部分不存在,则会创建一个新的对象(除非已经是路径的最后一部分)
451
+ *
452
+ * @param {Object} model - 包含要查询的数据的模型对象
453
+ * @param {string} path - 用点分隔的路径字符串,表示要访问的对象属性路径
454
+ * @returns {Object|undefined} - 返回目标对象,如果路径不存在则返回undefined
455
+ */
456
+ export function _GetTargetByPath(model, path) {
457
+ const arr = path.split(".");
458
+ return arr.reduce((prev, curr, index) => {
459
+ if (prev.hasOwnProperty(curr)) return prev[curr];
460
+ return (prev[curr] = index == arr.length - 1 ? undefined : {});
461
+ }, model);
462
+ }
463
+ /**
464
+ * 根据路径更新目标值
465
+ *
466
+ * 该函数通过一个点分隔的路径来更新一个对象中的嵌套属性值
467
+ * 它使用了reduce方法来遍历路径数组,并在路径的终点设置新的值
468
+ *
469
+ * @param {Object} model - 包含要更新数据的模型对象
470
+ * @param {string} path - 点分隔的字符串路径,指示如何到达目标属性
471
+ * @param {*} value - 要设置的新值
472
+ * @returns {*} - 返回更新后的模型对象中的值
473
+ */
474
+ export function _UpdateTargetByPath(model, path, value) {
475
+ const arr = path.split(".");
476
+ return arr.reduce((prev, curr, index) => {
477
+ if (index === arr.length - 1) prev[curr] = value;
478
+ return prev[curr];
479
+ }, model);
480
+ }