mazey 3.5.4 → 3.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts DELETED
@@ -1,2260 +0,0 @@
1
- /**
2
- * @author: Mazey Chu
3
- */
4
-
5
- /**
6
- * EN: Computes the longest common substring of two strings.
7
- *
8
- * ZH: 计算两个字符串的最长公共子串
9
- *
10
- * Usage:
11
- *
12
- * ```
13
- * calLongestCommonSubstring('fish', 'finish');
14
- * ```
15
- *
16
- * Output:
17
- *
18
- * ```
19
- * 3
20
- * ```
21
- *
22
- * @param {string} aStr String
23
- * @param {string} bStr String
24
- * @returns {number} Length
25
- */
26
- export function calLongestCommonSubstring(aStr: string, bStr: string): number {
27
- const aLen = aStr.length;
28
- const bLen = bStr.length;
29
- // 创建二维数组并且深拷贝
30
- const arr = deepCopyObject(new Array(aLen).fill(new Array(bLen).fill(0)));
31
- for (let i = 0; i < aLen; ++i) {
32
- for (let j = 0; j < bLen; ++j) {
33
- if (aStr[i] === bStr[j]) {
34
- let baseNum = 0;
35
- if (i > 0 && j > 0) {
36
- baseNum = arr[i - 1][j - 1];
37
- }
38
- arr[i][j] = baseNum + 1;
39
- }
40
- }
41
- }
42
- // 二维数组转一维数组
43
- const arr1 = Array.prototype.concat.apply([], arr);
44
- // 获取最长公共子串
45
- const maxLong = Math.max(...arr1);
46
- return maxLong;
47
- }
48
-
49
- /**
50
- * EN: Computes the longest common subsequence of two strings.
51
- *
52
- * ZH: 计算两个字符串的最长公共子序列
53
- *
54
- * Usage:
55
- *
56
- * ```
57
- * calLongestCommonSubsequence('fish', 'finish');
58
- * ```
59
- *
60
- * Output:
61
- *
62
- * ```
63
- * 4
64
- * ```
65
- *
66
- * @param {string} aStr 字符串
67
- * @param {string} bStr 字符串
68
- * @returns {number} 长度
69
- */
70
- export function calLongestCommonSubsequence(
71
- aStr: string,
72
- bStr: string
73
- ): number {
74
- const aLen = aStr.length;
75
- const bLen = bStr.length;
76
- // 创建二维数组并且深拷贝
77
- const arr = deepCopyObject(new Array(aLen).fill(new Array(bLen).fill(0)));
78
- for (let i = 0; i < aLen; ++i) {
79
- for (let j = 0; j < bLen; ++j) {
80
- if (aStr[i] === bStr[j]) {
81
- let baseNum = 0;
82
- if (i > 0 && j > 0) {
83
- baseNum = arr[i - 1][j - 1];
84
- }
85
- arr[i][j] = baseNum + 1;
86
- } else {
87
- let [leftValue, topValue] = [0, 0];
88
- if (j > 0) {
89
- leftValue = arr[i][j - 1];
90
- }
91
- if (i > 0) {
92
- topValue = arr[i - 1][j];
93
- }
94
- arr[i][j] = Math.max(leftValue, topValue);
95
- }
96
- }
97
- }
98
- // 二维数组转一维数组
99
- const arr1 = Array.prototype.concat.apply([], arr);
100
- // 获取最长公共子串
101
- const maxLong = Math.max(...arr1);
102
- return maxLong;
103
- }
104
-
105
- /**
106
- * Get the query param's value of the current Web URL(`location.search`).
107
- *
108
- * ```
109
- * // http://example.com/?t1=1&t2=2&t3=3&t4=4#2333
110
- * // ?t1=1&t2=2&t3=3&t4=4
111
- * getQueryParam('t3'); // 3
112
- * getQueryParam('t4'); // 4
113
- * ```
114
- *
115
- * @param {string} param Query param.
116
- * @returns {string} value
117
- * @category URL
118
- */
119
- export function getQueryParam(param: string): string {
120
- const reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)');
121
- const r = location.search.substr(1).match(reg);
122
- if (r !== null) {
123
- // return decodeURIComponent(unescape(r[2]));
124
- return decodeURIComponent(r[2]);
125
- }
126
- return '';
127
- }
128
-
129
- /**
130
- * Get the query param's value of the input URL.
131
- *
132
- * ```
133
- * getUrlParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't3'); // 3
134
- * getUrlParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't4'); // 4
135
- * ```
136
- *
137
- * @param {string} url URL string.
138
- * @param {string} param Query param.
139
- * @returns {string} value
140
- * @category URL
141
- */
142
- export function getUrlParam(url: string, param: string): string | string[] {
143
- const result: {
144
- [key: string]: string | string[] | any;
145
- } = {};
146
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
147
- url.replace(/\??(\w+)=([^&]*)&?/g, function(a, k, v): any {
148
- if (result[k] !== undefined) {
149
- const t = result[k];
150
- result[k] = [].concat(t, v);
151
- } else {
152
- result[k] = v;
153
- }
154
- });
155
- // if (param === undefined) {
156
- // return result;
157
- // } else {
158
- // return result[param] || '';
159
- // }
160
- return result[param] || '';
161
- }
162
-
163
- /**
164
- * Update the query param's value of the input URL.
165
- *
166
- * Usage:
167
- *
168
- * ```
169
- * updateQueryParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't3', 'three');
170
- * updateQueryParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't4', 'four');
171
- * ```
172
- *
173
- * Output:
174
- *
175
- * ```
176
- * http://example.com/?t1=1&t2=2&t3=three&t4=4
177
- * http://example.com/?t1=1&t2=2&t3=3&t4=four
178
- * ```
179
- *
180
- * @param {string} url URL string.
181
- * @param {string} param Query param.
182
- * @param {string} value Param's value.
183
- * @returns {string} URL.
184
- * @category URL
185
- */
186
- export function updateQueryParam(
187
- url: string,
188
- param: string,
189
- value: string
190
- ): string {
191
- const re = new RegExp('([?&])' + param + '=.*?(&|$)', 'i');
192
- const separator = url.indexOf('?') !== -1 ? '&' : '?';
193
- if (url.match(re)) {
194
- return url.replace(re, '$1' + param + '=' + value + '$2');
195
- } else {
196
- return url + separator + param + '=' + value;
197
- }
198
- }
199
-
200
- /**
201
- * Get the hash query param's value of the current Web URL(`location.hash`).
202
- *
203
- * Usage:
204
- *
205
- * ```
206
- * // http://example.com/?#2333?t1=1&t2=2&t3=3&t4=4
207
- * // #2333?t1=1&t2=2&t3=3&t4=4
208
- * getHashQueryParam('t3');
209
- * getHashQueryParam('t4');
210
- * ```
211
- *
212
- * Output:
213
- *
214
- * ```
215
- * 3
216
- * 4
217
- * ```
218
- *
219
- * @param {string} param Query param.
220
- * @returns {string} value
221
- * @category URL
222
- */
223
- export function getHashQueryParam(param: string): string {
224
- const hashs = location.hash.split('?');
225
- if (hashs.length === 1) {
226
- return '';
227
- }
228
- const reg = new RegExp(`(^|&)${param}=([^&]*)(&|$)`);
229
- const ret = hashs[1].match(reg);
230
- return ret ? ret[2] : '';
231
- }
232
-
233
- /**
234
- * Get the domain of URL, and other params.
235
- *
236
- * Usage:
237
- *
238
- * ```
239
- * getDomain('http://example.com/?t1=1&t2=2&t3=3&t4=4');
240
- * getDomain('http://example.com/test/thanks?t1=1&t2=2&t3=3&t4=4', ['hostname', 'pathname']);
241
- * ```
242
- *
243
- * Output:
244
- *
245
- * ```
246
- * example.com
247
- * example.com/test/thanks
248
- * ```
249
- *
250
- * @param {string} url
251
- * @param {array} rules Object.keys(location), ['href', 'protocol', 'host', 'hostname', 'port', 'pathname', 'search', 'hash'], ['hostname', 'pathname'] = 'km.mazey.net/plugins/servlet/mobile'
252
- * @category URL
253
- */
254
- export function getDomain(url: string, rules = ['hostname']): string {
255
- const aEl: any = document.createElement('a');
256
- aEl.href = url;
257
- return rules.reduce((ret, v) => {
258
- ret += aEl[v];
259
- return ret;
260
- }, '');
261
- }
262
-
263
- /**
264
- * Transfer CamelCase to KebabCase.
265
- *
266
- * ```
267
- * camelCaseToKebabCase('ABC'); // a-b-c
268
- * camelCaseToKebabCase('aBC'); // a-b-c
269
- * ```
270
- *
271
- * @param {string} camelCase 'aBC' or 'ABC'
272
- * @returns {string} 'a-b-c'
273
- */
274
- export function camelCaseToKebabCase(camelCase: string): string {
275
- const kebabCase = camelCase.replace(/([A-Z])/g, '-$1').toLowerCase();
276
- return kebabCase[0] === '-' ? kebabCase.substr(1) : kebabCase;
277
- }
278
-
279
- /**
280
- * Transfer CamelCase to Underscore.
281
- *
282
- * ```
283
- * camelCase2Underscore('ABC'); // a_b_c
284
- * camelCase2Underscore('aBC'); // a_b_c
285
- * ```
286
- *
287
- * @param {string} camelCase 'aBC' or 'ABC'
288
- * @returns {string} 'a_b_c'
289
- */
290
- export function camelCase2Underscore(camelCase: string): string {
291
- const kebabCase = camelCase.replace(/([A-Z])/g, '_$1').toLowerCase();
292
- return kebabCase[0] === '_' ? kebabCase.substr(1) : kebabCase;
293
- }
294
-
295
- /**
296
- * Remove leading and trailing whitespace or specified characters from string.
297
- *
298
- * ```
299
- * mTrim(' 1 2 3 '); // '1 2 3'
300
- * mTrim('abc '); // 'abc'
301
- * ```
302
- *
303
- * @param {string} str The string to trim.
304
- * @returns {string} Trimmed string.
305
- */
306
- export function mTrim(str: string): string {
307
- str = str.replace(/^\s+/, ''); // 去除头部空格
308
- let end = str.length - 1;
309
- const ws = /\s/;
310
- while (ws.test(str.charAt(end))) {
311
- end--; // 最后一个非空格字符的索引
312
- }
313
- return str.slice(0, end + 1);
314
- }
315
-
316
- /**
317
- * @method newLine
318
- * @description Make a newline of HTML.
319
- * @param {string} str The string to make a newline.
320
- * @returns {string} A newline with `br`.
321
- */
322
- export function newLine(str: string): string {
323
- if (!str) {
324
- return '';
325
- }
326
- const reg = new RegExp('\\n', 'g');
327
- return str.replace(reg, '<br />');
328
- }
329
-
330
- /**
331
- * Clone Object deeply.
332
- *
333
- * Usage:
334
- *
335
- * ```
336
- * deepCopyObject(['a', 'b', 'c']);
337
- * deepCopyObject('abc');
338
- * ```
339
- *
340
- * Output:
341
- *
342
- * ```
343
- * ['a', 'b', 'c']
344
- * 'abc'
345
- * ```
346
- *
347
- * @param {object} obj The value to clone.
348
- * @returns {object} Returns the deep cloned value.
349
- */
350
- export function deepCopyObject(obj: any): any {
351
- return JSON.parse(JSON.stringify(obj));
352
- }
353
-
354
- /**
355
- * Check whether it is a valid JSON string.
356
- *
357
- * Usage:
358
- *
359
- * ```
360
- * isJsonString(`['a', 'b', 'c']`);
361
- * isJsonString(`["a", "b", "c"]`);
362
- * ```
363
- *
364
- * Output:
365
- *
366
- * ```
367
- * false
368
- * true
369
- * ```
370
- */
371
- export function isJsonString(str: string): boolean {
372
- try {
373
- if (typeof JSON.parse(str) === 'object') {
374
- return true;
375
- }
376
- } catch (e) {
377
- /* pass */
378
- }
379
- return false;
380
- }
381
-
382
- /**
383
- * @method generateRndNum
384
- * @description Produce a random string of number, `generateRndNum(7)` => '7658495'.
385
- * @param {number} n Length
386
- * @returns {string} Return the random string.
387
- */
388
- export function generateRndNum(n = 5): string {
389
- let ret = '';
390
- while (n--) {
391
- ret += Math.floor(Math.random() * 10);
392
- }
393
- return ret;
394
- }
395
-
396
- /**
397
- * @method generateUniqueNum
398
- * @description 根据时间生成唯一标志的数字 mGenerateUniqueNum() => 1538324722364123。
399
- * @param {number} n 随机数的长度
400
- */
401
- export function generateUniqueNum(n = 3): string {
402
- const [now, rnd] = [mNow(), generateRndNum(n || 3)];
403
- return now + rnd;
404
- }
405
-
406
- /**
407
- * @method floatToPercent
408
- * @description 浮点数转为百分比 0.2 => 20%。
409
- * @param {number} num 浮点数
410
- * @param {number} fixSize 保留几位浮点数
411
- */
412
- export function floatToPercent(num: number, fixSize = 0): string {
413
- let ret = '';
414
- if (fixSize) {
415
- ret = (num * 100).toFixed(fixSize);
416
- } else {
417
- ret = String(Math.floor(num * 100));
418
- }
419
- return `${ret}%`;
420
- }
421
-
422
- /**
423
- * @method floatFixed
424
- * @description 浮点数保留指定位。
425
- */
426
- export function floatFixed(num: string, size = 0): string {
427
- return parseFloat(num).toFixed(size);
428
- }
429
-
430
- /**
431
- * @method cancelBubble
432
- * @description 阻止冒泡。
433
- */
434
- export function cancelBubble(e: any): void {
435
- const ev = e || window.event;
436
- if (ev.stopPropagation) {
437
- // W3C
438
- ev.stopPropagation();
439
- } else {
440
- // IE
441
- ev.cancelBubble = true;
442
- }
443
- }
444
-
445
- /**
446
- * @method hasClass
447
- */
448
- export function hasClass(obj: any, cls: string): boolean {
449
- const oriCls = obj.className; // 获取对象的class值
450
- const oriClsArr = oriCls.split(/\s+/); // 分隔空格转换成数组
451
- for (let i = 0; i < oriClsArr.length; i++) {
452
- if (oriClsArr[i] === cls) {
453
- return true; // 若匹配到class则返回True
454
- }
455
- }
456
- return false; // 否则返回False
457
- }
458
-
459
- /**
460
- * @method addClass
461
- */
462
- export function addClass(obj: any, cls: string): void {
463
- const oriCls = obj.className;
464
- let space = '';
465
- let newCls = ''; // 获取对象的class值
466
- if (oriCls !== '') {
467
- space = ' '; // 若原来的class不为空,跟一个空格
468
- }
469
- newCls = oriCls + space + cls; // 将新的class加进去
470
- obj.className = newCls; // 替换新class
471
- }
472
-
473
- /**
474
- * @method removeClass
475
- */
476
- export function removeClass(obj: any, cls: string): void {
477
- const oriCls = obj.className;
478
- let newCls; // 获取对象的class值
479
- newCls = ' ' + oriCls + ' '; // 前后加空格
480
- newCls = newCls.replace(/(\s+)/gi, ' '); // 将多余的空格替换成一个空格
481
- newCls = newCls.replace(' ' + cls + ' ', ' '); // 将加了前后空格的cls替换成空格' '
482
- newCls = newCls.replace(/(^\s+)|(\s+$)/g, ''); // 去掉前后空格
483
- obj.className = newCls;
484
- }
485
-
486
- /**
487
- * EN: Throttle
488
- *
489
- * ZH: 节流
490
- *
491
- * ```
492
- * const foo = throttle(() => {
493
- * console.log('The function will be invoked at most once per every wait 1000 milliseconds.');
494
- * }, 1000, { leading: true });
495
- * ```
496
- *
497
- * Reference: [Lodash](https://lodash.com/docs/4.17.15#throttle)
498
- */
499
- export function throttle(
500
- func: any,
501
- wait: number,
502
- options: { leading?: boolean; trailing?: boolean } = {}
503
- ): any {
504
- options = Object.assign({}, options);
505
- // timeout: setTimeout Handle
506
- // previous: 上次时间戳
507
- let context: any = null;
508
- let args: any = null;
509
- let timeout: any = null;
510
- let [result, previous] = [null, 0];
511
- // if (!options) {
512
- // options = {};
513
- // }
514
- const later = function() {
515
- previous = options.leading === false ? 0 : mNow();
516
- timeout = null;
517
- result = func.apply(context, args);
518
- if (!timeout) {
519
- context = args = null;
520
- }
521
- };
522
- return function(...argRest: Array<any>) {
523
- const now = mNow();
524
- if (!previous && options.leading === false) {
525
- previous = now;
526
- }
527
- const remaining = wait - (now - previous);
528
- context = this;
529
- args = argRest;
530
- if (remaining <= 0 || remaining > wait) {
531
- if (timeout) {
532
- clearTimeout(timeout);
533
- timeout = null;
534
- }
535
- previous = now;
536
- result = func.apply(context, args);
537
- if (!timeout) {
538
- context = args = null;
539
- }
540
- } else if (!timeout && options.trailing !== false) {
541
- timeout = setTimeout(later, remaining);
542
- }
543
- return result;
544
- };
545
- }
546
-
547
- /**
548
- * EN: Debounce
549
- *
550
- * ZH: 去抖
551
- *
552
- * ```
553
- * const foo = debounce(() => {
554
- * console.log('The debounced function will only be invoked in 1000 milliseconds, the other invoking will disappear during the wait time.');
555
- * }, 1000, true);
556
- * ```
557
- */
558
- export function debounce(func: any, wait: number, immediate?: any): any {
559
- let context: any = null;
560
- let timeout: any = null;
561
- let timestamp: any = null;
562
- let args: any = null;
563
- let [result] = [null];
564
- const later = function() {
565
- const last = mNow() - timestamp;
566
- if (last < wait && last >= 0) {
567
- timeout = setTimeout(later, wait - last);
568
- } else {
569
- timeout = null;
570
- if (!immediate) {
571
- result = func.apply(context, args);
572
- if (!timeout) {
573
- context = args = null;
574
- }
575
- }
576
- }
577
- };
578
- return function(...argRest: Array<any>) {
579
- context = this;
580
- args = argRest;
581
- timestamp = mNow();
582
- const callNow = immediate && !timeout;
583
- if (!timeout) {
584
- timeout = setTimeout(later, wait);
585
- }
586
- if (callNow) {
587
- result = func.apply(context, args);
588
- context = args = null;
589
- }
590
- return result;
591
- };
592
- }
593
-
594
- /**
595
- * @method friendlyInterval
596
- * @description 获取间隔时间。
597
- * @param {number/Date} start 开始时间戳 1585325367122
598
- * @param {number/Date} end 结束时间戳 1585325367122
599
- * @param {string} options.type 返回类型 d: 2(天) text: 2 天 4 时...
600
- * @returns {string/number} 取决于 type
601
- */
602
- export function friendlyInterval(
603
- start = 0,
604
- end = 0,
605
- options: { type?: string } = { type: 'd' }
606
- ): number | string {
607
- const { type } = options;
608
- if (!isNumber(start)) start = new Date(start).getTime();
609
- if (!isNumber(end)) end = new Date(end).getTime();
610
- const t = end - start;
611
- let ret = '';
612
- let [d, h, m, s] = new Array(4).fill(0);
613
- if (t >= 0) {
614
- d = Math.floor(t / 1000 / 60 / 60 / 24);
615
- h = Math.floor(t / 1000 / 60 / 60);
616
- m = Math.floor(t / 1000 / 60);
617
- s = Math.floor(t / 1000);
618
- switch (type) {
619
- case 'd':
620
- ret = d;
621
- break;
622
- case 'text':
623
- d = Math.floor(t / 1000 / 60 / 60 / 24);
624
- h = Math.floor((t / 1000 / 60 / 60) % 24);
625
- m = Math.floor((t / 1000 / 60) % 60);
626
- s = Math.floor((t / 1000) % 60);
627
- ret = d + ' 天 ' + h + ' 时 ' + m + ' 分 ' + s + ' 秒';
628
- break;
629
- default:
630
- ret = s;
631
- }
632
- }
633
- return ret;
634
- }
635
-
636
- /**
637
- * EN: Check whether it is a right number.
638
- *
639
- * ZH: 判断是否有效数字
640
- *
641
- * ```
642
- * isNumber(123); // true
643
- * isNumber('123'); // false
644
- * // Default: NaN, Infinity is not Number
645
- * isNumber(Infinity); // false
646
- * isNumber(Infinity, { isUnFiniteAsNumber: true }); // true
647
- * isNumber(NaN); // false
648
- * isNumber(NaN, { isNaNAsNumber: true, isUnFiniteAsNumber: true }); // true
649
- * ```
650
- *
651
- * @param {*} num 被判断的值
652
- * @param {boolean} options.isNaNAsNumber 是否 NaN 算数字(默认不算)
653
- * @param {boolean} options.isUnFiniteAsNumber 是否 无限 算数字(默认不算)
654
- * @returns {boolean} true 是数字
655
- */
656
- export function isNumber(
657
- num: any,
658
- options: { isNaNAsNumber?: boolean; isUnFiniteAsNumber?: boolean } = {
659
- isNaNAsNumber: false,
660
- isUnFiniteAsNumber: false
661
- }
662
- ): boolean {
663
- const { isNaNAsNumber, isUnFiniteAsNumber } = Object.assign(
664
- { isNaNAsNumber: false, isUnFiniteAsNumber: false },
665
- options
666
- );
667
- let ret = true;
668
- // 数字类型
669
- if (typeof num !== 'number') {
670
- ret = false;
671
- }
672
- // 无限值
673
- if (isUnFiniteAsNumber === false && !isFinite(num)) {
674
- // console.log('1333');
675
- ret = false;
676
- }
677
- // NaN
678
- if (isNaNAsNumber === false && isNaN(num)) {
679
- // console.log('2333');
680
- ret = false;
681
- }
682
- return ret;
683
- }
684
-
685
- /**
686
- * @method doFn
687
- * @description 执行有效函数
688
- * @param {function} fn 等待被执行的未知是否有效的函数
689
- */
690
- export function doFn(fn: any, ...params: any[]): any {
691
- let ret = null;
692
- if (fn && typeof fn === 'function') {
693
- ret = fn(...params);
694
- }
695
- return ret;
696
- }
697
-
698
- /**
699
- * @method setSessionStorage
700
- * @description 存储数据到 sessionStorage
701
- * @param {string} key 键
702
- * @param {string} value 值
703
- */
704
- export function setSessionStorage(key: string, value: any = null): void {
705
- if (key) {
706
- sessionStorage.setItem(key, JSON.stringify(value));
707
- }
708
- }
709
-
710
- /**
711
- * @method getSessionStorage
712
- * @description 存储数据到 sessionStorage
713
- * @param {string} key 键
714
- * @returns {*} 返回值
715
- */
716
- export function getSessionStorage(key: string): any {
717
- let ret = null;
718
- if (key) {
719
- const value = sessionStorage.getItem(key);
720
- if (value) {
721
- ret = JSON.parse(value);
722
- }
723
- }
724
- return ret;
725
- }
726
-
727
- /**
728
- * @method setLocalStorage
729
- * @description 存储数据到 localStorage
730
- * @param {string} key 键
731
- * @param {string} value 值
732
- */
733
- export function setLocalStorage(key: string, value: any = null): void {
734
- if (key) {
735
- localStorage.setItem(key, JSON.stringify(value));
736
- }
737
- }
738
-
739
- /**
740
- * @method getLocalStorage
741
- * @description 存储数据到 localStorage
742
- * @param {string} key 键
743
- * @returns {*} 返回值
744
- */
745
- export function getLocalStorage(key: string): any {
746
- let ret = null;
747
- if (key) {
748
- const value = localStorage.getItem(key);
749
- if (value) {
750
- ret = JSON.parse(value);
751
- }
752
- }
753
- return ret;
754
- }
755
-
756
- /**
757
- * EN: Load a CSS file from the server.
758
- *
759
- * ZH: 动态加载 CSS 文件
760
- *
761
- * ```
762
- * loadCSS(
763
- * 'http://example.com/css/mazey-base.css',
764
- * {
765
- * id: 'iamid', // Optional, link ID, default none
766
- * }
767
- * )
768
- * .then(
769
- * res => {
770
- * console.log(`Load CSS Success: ${res}`);
771
- * }
772
- * )
773
- * .catch(
774
- * err => {
775
- * console.error(`Load CSS Fail: ${err.message}`)
776
- * }
777
- * );
778
- * ```
779
- *
780
- * @param {string} url -- css资源路径
781
- * @param {string} options.id -- link标签id
782
- * @returns {Promise<boolean>} true -- 加载成功
783
- * @category Load Resource
784
- */
785
- export function loadCSS(
786
- url: string,
787
- options: { id?: string } = { id: '' }
788
- ): Promise<boolean | Error | any> {
789
- const { id } = options;
790
- let success: (v: boolean) => void;
791
- let fail: (v: Error) => void;
792
- const status = new Promise((resolve, reject) => {
793
- [success, fail] = [resolve, reject];
794
- });
795
- // const tempCB = (typeof callback === 'function' ? callback : function () { });
796
- const callback = function() {
797
- // doFn(success, true);
798
- success(true);
799
- };
800
- let node: any = document.createElement('link');
801
- const supportOnload = 'onload' in node;
802
- const isOldWebKit =
803
- +navigator.userAgent.replace(
804
- /.*(?:AppleWebKit|AndroidWebKit)\/?(\d+).*/i,
805
- '$1'
806
- ) < 536; // webkit旧内核做特殊处理
807
- const protectNum = 300000; // 阈值10分钟,一秒钟执行pollCss 500次
808
-
809
- node.rel = 'stylesheet';
810
- node.type = 'text/css';
811
- node.href = url;
812
- if (typeof id !== 'undefined') {
813
- node.id = id;
814
- }
815
- document.getElementsByTagName('head')[0].appendChild(node);
816
-
817
- // for Old WebKit and Old Firefox
818
- if (isOldWebKit || !supportOnload) {
819
- // Begin after node insertion
820
- setTimeout(function() {
821
- pollCss(node, callback, 0);
822
- }, 1);
823
- return status;
824
- }
825
-
826
- if (supportOnload) {
827
- node.onload = onload;
828
- node.onerror = function() {
829
- // 加载失败(404)
830
- onload();
831
- };
832
- } else {
833
- // todo: 和 !supportOnload 重复
834
- node.onreadystatechange = function() {
835
- if (/loaded|complete/.test(node.readyState)) {
836
- onload();
837
- }
838
- };
839
- }
840
-
841
- function onload() {
842
- // 确保只跑一次下载操作
843
- node.onload = node.onerror = node.onreadystatechange = null;
844
-
845
- // 清空node引用,在低版本IE,不清除会造成内存泄露
846
- node = null;
847
-
848
- callback();
849
- }
850
-
851
- // 循环判断css是否已加载成功
852
- /*
853
- * @param node -- link节点
854
- * @param callback -- 回调函数
855
- * @param step -- 计步器,避免无限循环
856
- */
857
- function pollCss(node: any, callback: any, step: number) {
858
- const sheet = node.sheet;
859
- let isLoaded: any;
860
-
861
- step += 1;
862
-
863
- // 保护,大于10分钟,则不再轮询
864
- if (step > protectNum) {
865
- isLoaded = true;
866
-
867
- // 清空node引用
868
- node = null;
869
-
870
- callback();
871
- return;
872
- }
873
-
874
- if (isOldWebKit) {
875
- // for WebKit < 536
876
- if (sheet) {
877
- isLoaded = true;
878
- }
879
- } else if (sheet) {
880
- // for Firefox < 9.0
881
- try {
882
- if (sheet.cssRules) {
883
- isLoaded = true;
884
- }
885
- } catch (ex) {
886
- // 火狐特殊版本,通过特定值获知是否下载成功
887
- // The value of `ex.name` is changed from "NS_ERROR_DOM_SECURITY_ERR"
888
- // to "SecurityError" since Firefox 13.0. But Firefox is less than 9.0
889
- // in here, So it is ok to just rely on "NS_ERROR_DOM_SECURITY_ERR"
890
- if ((ex as any).name === 'NS_ERROR_DOM_SECURITY_ERR') {
891
- isLoaded = true;
892
- }
893
- }
894
- }
895
-
896
- setTimeout(function() {
897
- if (isLoaded) {
898
- // 延迟20ms是为了给下载的样式留够渲染的时间
899
- callback();
900
- } else {
901
- pollCss(node, callback, step);
902
- }
903
- }, 20);
904
- }
905
- return status;
906
- }
907
-
908
- /**
909
- * EN: Load a JavaScript file from the server and execute it.
910
- *
911
- * ZH: 动态加载 JavaScript 文件
912
- *
913
- * ```
914
- * loadScript(
915
- * 'http://example.com/static/js/plugin-2.1.1.min.js',
916
- * {
917
- * id: 'iamid', // (Optional) script ID, default none
918
- * timeout: 5000, // (Optional) timeout, default `5000`
919
- * isDefer: false, // (Optional) defer, default `false`
920
- * }
921
- * )
922
- * .then(
923
- * res => {
924
- * console.log(`Load JavaScript script: ${res}`);
925
- * }
926
- * )
927
- * .catch(
928
- * err => {
929
- * console.error(`Load JavaScript script: ${err.message}`)
930
- * }
931
- * );
932
- * ```
933
- *
934
- * @param {string} url -- JavaScript 资源路径
935
- * @param {string} options.id -- DOM ID
936
- * @param {function} options.callback -- 加载后回调函数
937
- * @param {number} options.timeout -- 超时时长
938
- * @param {boolean} options.isDefer -- 是否添加 defer 标签
939
- * @returns {Promise<boolean>} -- true 成功
940
- * @category Load Resource
941
- */
942
- export function loadScript(
943
- url: string,
944
- options: {
945
- id?: string;
946
- callback?: (...params: any[]) => any;
947
- timeout?: number;
948
- isDefer?: boolean;
949
- } = {
950
- id: '',
951
- callback: function() {
952
- /* pass */
953
- },
954
- timeout: 5000,
955
- isDefer: false
956
- }
957
- ): Promise<boolean | string | Error> {
958
- const { id, callback, timeout, isDefer } = Object.assign(
959
- {
960
- id: '',
961
- callback: function() {
962
- /* pass */
963
- },
964
- timeout: 5000,
965
- isDefer: false
966
- },
967
- options
968
- );
969
- let success: any = null;
970
- let fail: any = null;
971
- const script: any = document.createElement('script');
972
- // 如果没有 script 标签,那么代码就不会运行。可以利用这一事实,在页面的第一个 script 标签上使用 insertBefore()。
973
- const firstScript: any = document.getElementsByTagName('script')[0];
974
- script.type = 'text/javascript';
975
- if (isDefer) {
976
- script.defer = 'defer';
977
- }
978
- if (id) {
979
- script.id = id;
980
- }
981
- if (script.readyState) {
982
- // IE
983
- script.onreadystatechange = function() {
984
- if (script.readyState === 'loaded' || script.readyState === 'complete') {
985
- script.onreadystatechange = null;
986
- doFn(callback);
987
- doFn(success, true);
988
- }
989
- };
990
- } else {
991
- // Others
992
- script.onload = function() {
993
- doFn(callback);
994
- doFn(success, true);
995
- };
996
- }
997
- script.src = url;
998
- firstScript && firstScript.parentNode.insertBefore(script, firstScript);
999
- return new Promise((resolve, reject) => {
1000
- [success, fail] = [resolve, reject];
1001
- if (timeout) {
1002
- setTimeout(fail.bind(null, Error('timeout')), timeout);
1003
- }
1004
- });
1005
- }
1006
-
1007
- /**
1008
- * @method mNow
1009
- * @description 获取时间戳
1010
- */
1011
- export function mNow(): number {
1012
- let ret = 0;
1013
- if (Date.now) {
1014
- ret = Date.now();
1015
- } else {
1016
- ret = new Date().getTime();
1017
- }
1018
- return ret;
1019
- }
1020
-
1021
- /**
1022
- * @method setCookie
1023
- * @description 设置 Cookie
1024
- */
1025
- export function setCookie(
1026
- name: string,
1027
- value: string,
1028
- days: number,
1029
- domain: string
1030
- ): void {
1031
- let domainParts, expires;
1032
- let date: any;
1033
- if (days) {
1034
- date = new Date();
1035
- date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
1036
- expires = '; expires=' + date.toGMTString();
1037
- } else {
1038
- expires = '';
1039
- }
1040
- const host = location.host;
1041
- if (host.split('.').length === 1) {
1042
- // no "." in a domain - it's localhost or something similar
1043
- document.cookie = name + '=' + value + expires + '; path=/';
1044
- } else {
1045
- // Remember the cookie on all subdomains.
1046
- //
1047
- // Start with trying to set cookie to the top domain.
1048
- // (example: if user is on foo.com, try to set
1049
- // cookie to domain ".com")
1050
- //
1051
- // If the cookie will not be set, it means ".com"
1052
- // is a top level domain and we need to
1053
- // set the cookie to ".foo.com"
1054
- domainParts = host.split('.');
1055
- domainParts.shift();
1056
- domain = domain || '.' + domainParts.join('.');
1057
- document.cookie =
1058
- name + '=' + value + expires + '; path=/; domain=' + domain;
1059
- // check if cookie was successfuly set to the given domain
1060
- // (otherwise it was a Top-Level Domain)
1061
- if (getCookie(name) === null || getCookie(name) !== value) {
1062
- // append "." to current domain
1063
- domain = domain || '.' + host;
1064
- document.cookie =
1065
- name + '=' + value + expires + '; path=/; domain=' + domain;
1066
- }
1067
- }
1068
- }
1069
-
1070
- /**
1071
- * @method getCookie
1072
- * @description 获取 Cookie
1073
- */
1074
- export function getCookie(name: string): string {
1075
- const nameEQ = name + '=';
1076
- const ca = document.cookie.split(';');
1077
- for (let i = 0; i < ca.length; i++) {
1078
- let c = ca[i];
1079
- while (c.charAt(0) == ' ') {
1080
- c = c.substring(1, c.length);
1081
- }
1082
- if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
1083
- }
1084
- return '';
1085
- }
1086
-
1087
- /**
1088
- * @hidden
1089
- */
1090
- interface WebPerformance {
1091
- [key: string]: string | number;
1092
- }
1093
-
1094
- /**
1095
- * EN: Get page load time(PerformanceTiming).
1096
- *
1097
- * ZH: 获取页面加载相关的各项数据
1098
- *
1099
- * Usage:
1100
- *
1101
- * ```
1102
- * // `camelCase:false` (Default) Return underline data.
1103
- * // `camelCase:true` Return hump data.
1104
- * getPerformance()
1105
- * .then(res => {
1106
- * console.log(JSON.stringify(res));
1107
- * })
1108
- * .catch(console.error);
1109
- * ```
1110
- *
1111
- * Output:
1112
- *
1113
- * ```
1114
- * {"os":"ios","os_version":"13_2_3","device_type":"phone","network":"4g","unload_time":0,"redirect_time":0,"dns_time":0,"tcp_time":0,"response_time":289,"download_time":762,"first_paint_time":469,"first_contentful_paint_time":469,"domready_time":1318,"onload_time":2767,"white_time":299,"render_time":2768,"decoded_body_size":979570,"encoded_body_size":324938}
1115
- * ```
1116
- *
1117
- * Results:
1118
- *
1119
- * | Index | Field | Description |
1120
- * | --- | --- | --- |
1121
- * | DNS lookup | dns_time | domainLookupEnd - domainLookupStart |
1122
- * | Connection negotiation | tcp_time | connectEnd - connectStart |
1123
- * | Requests and responses | response_time | responseStart - requestStart |
1124
- * | White screen | white_time | responseStart - navigationStart |
1125
- * | DomReady | domready_time | domContentLoadedEventStart - navigationStart |
1126
- * | Onload | onload_time | loadEventStart - navigationStart |
1127
- * | EventEnd | render_time | loadEventEnd -navigationStart |
1128
- * | Unload | unload_time | (Optional) unloadEventEnd - unloadEventStart |
1129
- * | Redirect | redirect_time | (Optional) redirectEnd - redirectStart |
1130
- * | SSL | ssl_time | (Optional) connectEnd - secureConnectionStart |
1131
- * | Download | download_time | (Optional) responseEnd - responseStart |
1132
- *
1133
- * @param {boolean} camelCase -- false(默认) 以下划线形式返回数据 true 以驼峰形式返回数据
1134
- * @returns {Promise<object>} 加载数据
1135
- */
1136
- export function getPerformance(
1137
- camelCase = false
1138
- ): Promise<WebPerformance | Error> {
1139
- let success: (v: WebPerformance) => void;
1140
- let fail: (v: Error) => void;
1141
- const status: Promise<WebPerformance> = new Promise((resolve, reject) => {
1142
- [success, fail] = [resolve, reject];
1143
- });
1144
- const timing = window.performance.timing;
1145
- const startTime = timing.navigationStart || timing.fetchStart;
1146
- let firstPaintTime: any;
1147
- let firstContentfulPaintTime: any;
1148
- // 是否已经形成数据(页面加载完成之后)
1149
- if (
1150
- window.performance &&
1151
- window.performance.timing &&
1152
- window.performance.timing.loadEventEnd > 0
1153
- ) {
1154
- // console.log('created')
1155
- getTiming();
1156
- } else {
1157
- // console.log('creating')
1158
- window.addEventListener('load', function() {
1159
- //不能影响最后的时间计算
1160
- window.setTimeout(function() {
1161
- getTiming();
1162
- }, 0);
1163
- });
1164
- }
1165
- // performance
1166
- function getTiming() {
1167
- // 获取首次渲染时间
1168
- try {
1169
- if (window.performance && Boolean(window.performance.getEntriesByType)) {
1170
- const performance = window.performance;
1171
- const performanceEntries = performance.getEntriesByType('paint');
1172
- performanceEntries.forEach((performanceEntry, i, entries) => {
1173
- const startTime = Math.round(performanceEntry.startTime);
1174
- if (performanceEntry.name === 'first-paint')
1175
- firstPaintTime = startTime;
1176
- else if (performanceEntry.name === 'first-contentful-paint')
1177
- firstContentfulPaintTime = startTime;
1178
- });
1179
- } else {
1180
- console.error('paint');
1181
- }
1182
- } catch (e) {
1183
- console.error((e as any).message);
1184
- }
1185
- // 获取加载时间
1186
- if (
1187
- window.performance &&
1188
- typeof window.performance.getEntries === 'function'
1189
- ) {
1190
- const performanceNavigationTiming: any =
1191
- (window.performance.getEntries() || [])[0] || {};
1192
- const data: any = {
1193
- // url: encodeURI(location.href),
1194
- // ua: navigator.userAgent,
1195
- os: getOS(),
1196
- osVersion: getOSVersion(),
1197
- deviceType: getDeviceType(),
1198
- network: getNetWork(),
1199
- screenDirection: getOrientationStatu(),
1200
- unloadTime: timing.unloadEventEnd - timing.unloadEventStart, //上个文档的卸载时间
1201
- redirectTime: timing.redirectEnd - timing.redirectStart, //*重定向时间
1202
- dnsTime: timing.domainLookupEnd - timing.domainLookupStart, //*DNS查询时间
1203
- tcpTime: timing.connectEnd - timing.connectStart, //*服务器连接时间
1204
- sslTime: getSSLTime(timing.connectEnd, timing.secureConnectionStart), //*ssl连接时间
1205
- responseTime: timing.responseStart - timing.requestStart, //*服务器响应时间
1206
- downloadTime: timing.responseEnd - timing.responseStart, //*网页下载时间
1207
- firstPaintTime: firstPaintTime, //*首次渲染时间
1208
- firstContentfulPaintTime: firstContentfulPaintTime, //*首次渲染内容时间
1209
- domreadyTime: timing.domContentLoadedEventStart - startTime || 0, //*dom ready时间(总和)
1210
- onloadTime: timing.loadEventStart - startTime || 0, //*onload时间(总和)
1211
- whiteTime: timing.responseStart - startTime, //*白屏时间
1212
- renderTime: timing.loadEventEnd - startTime || 0, //整个过程的时间之和
1213
- decodedBodySize: performanceNavigationTiming.decodedBodySize || '', //页面压缩前大小
1214
- encodedBodySize: performanceNavigationTiming.encodedBodySize || '' //页面压缩后大小
1215
- };
1216
- // 过滤异常数据
1217
- Object.keys(data).forEach(k => {
1218
- // 过滤掉 <0 的数据
1219
- if (isNumber(data[k]) && data[k] < 0) {
1220
- data[k] = 0;
1221
- }
1222
- });
1223
- // 过滤掉白屏时间 > onload 的数据
1224
- if (isNumber(data.whiteTime) && data.whiteTime > data.onloadTime) {
1225
- data.whiteTime = 0;
1226
- }
1227
- if (startTime > 0) {
1228
- let Underscore: any;
1229
- if (!camelCase) {
1230
- Object.keys(data).forEach(k => {
1231
- if (!Underscore) Underscore = {};
1232
- // console.log('camelCase2Underscore', k, data, )
1233
- Underscore[camelCase2Underscore(k)] = data[k];
1234
- });
1235
- }
1236
- success(Underscore || data);
1237
- } else {
1238
- fail(Error('startTime'));
1239
- }
1240
- } else {
1241
- fail(Error('getEntries'));
1242
- }
1243
- }
1244
- //获取当前操作系统
1245
- function getOS() {
1246
- let os;
1247
- if (
1248
- navigator.userAgent.indexOf('Android') > -1 ||
1249
- navigator.userAgent.indexOf('Linux') > -1
1250
- ) {
1251
- os = 'android';
1252
- } else if (navigator.userAgent.indexOf('iPhone') > -1) {
1253
- os = 'ios';
1254
- } else if (navigator.userAgent.indexOf('Windows Phone') > -1) {
1255
- os = 'wp';
1256
- } else {
1257
- os = 'others';
1258
- }
1259
- return os;
1260
- }
1261
- // 获取操作系统版本
1262
- function getOSVersion() {
1263
- let OSVision: any;
1264
- const u = navigator.userAgent;
1265
- const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //Android
1266
- const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
1267
- if (isAndroid) {
1268
- OSVision = (navigator.userAgent.split(';')[1].match(/\d+\.\d+/g) ||
1269
- [])[0];
1270
- }
1271
- if (isIOS) {
1272
- OSVision = (navigator.userAgent
1273
- .split(';')[1]
1274
- .match(/(\d+)_(\d+)_?(\d+)?/) || [])[0];
1275
- }
1276
- return OSVision;
1277
- }
1278
- //获取设备类型
1279
- function getDeviceType() {
1280
- let deviceType;
1281
- const sUserAgent = navigator.userAgent.toLowerCase();
1282
- const bIsIpad = sUserAgent.match(/(ipad)/i) && 'ipad';
1283
- const bIsIphoneOs = sUserAgent.match(/iphone os/i) && 'iphone os';
1284
- const bIsMidp = sUserAgent.match(/midp/i) && 'midp';
1285
- const bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) && 'rv:1.2.3.4';
1286
- const bIsUc = sUserAgent.match(/ucweb/i) && 'ucweb';
1287
- const bIsAndroid = sUserAgent.match(/android/i) && 'android';
1288
- const bIsCE = sUserAgent.match(/windows ce/i) && 'windows ce';
1289
- const bIsWM = sUserAgent.match(/windows mobile/i) && 'windows mobile';
1290
- if (
1291
- !(
1292
- bIsIpad ||
1293
- bIsIphoneOs ||
1294
- bIsMidp ||
1295
- bIsUc7 ||
1296
- bIsUc ||
1297
- bIsAndroid ||
1298
- bIsCE ||
1299
- bIsWM
1300
- )
1301
- ) {
1302
- deviceType = 'pc'; //pc
1303
- } else if (
1304
- bIsIphoneOs ||
1305
- bIsMidp ||
1306
- bIsUc7 ||
1307
- bIsUc ||
1308
- bIsAndroid ||
1309
- bIsCE ||
1310
- bIsWM
1311
- ) {
1312
- deviceType = 'phone'; //phone
1313
- } else if (bIsIpad) {
1314
- deviceType = 'ipad'; //ipad
1315
- } else {
1316
- deviceType = undefined;
1317
- }
1318
- return deviceType;
1319
- }
1320
- // 获取网络状态
1321
- function getNetWork() {
1322
- let netWork: any;
1323
- if (
1324
- (navigator as any).connection &&
1325
- (navigator as any).connection.effectiveType
1326
- ) {
1327
- switch ((navigator as any).connection.effectiveType) {
1328
- case 'wifi':
1329
- netWork = 'wifi'; // wifi
1330
- break;
1331
- case '4g':
1332
- netWork = '4g'; // 4g
1333
- break;
1334
- case '2g':
1335
- netWork = '2g'; // 2g
1336
- break;
1337
- case '3g':
1338
- netWork = '3g'; // 3g
1339
- break;
1340
- case 'ethernet':
1341
- netWork = 'ethernet'; // ethernet
1342
- break;
1343
- case 'default':
1344
- netWork = undefined; // 未知
1345
- break;
1346
- }
1347
- }
1348
- return netWork;
1349
- }
1350
- // 获取横竖屏状态
1351
- function getOrientationStatu() {
1352
- let orientationStatu: any;
1353
- if (
1354
- window.screen &&
1355
- window.screen.orientation &&
1356
- window.screen.orientation.angle
1357
- ) {
1358
- if (
1359
- window.screen.orientation.angle === 180 ||
1360
- window.screen.orientation.angle === 0
1361
- ) {
1362
- // 竖屏
1363
- orientationStatu = '|';
1364
- }
1365
- if (
1366
- window.screen.orientation.angle === 90 ||
1367
- window.screen.orientation.angle === -90
1368
- ) {
1369
- // 横屏
1370
- orientationStatu = '-';
1371
- }
1372
- }
1373
- return orientationStatu;
1374
- }
1375
- // 获取ssl连接时间
1376
- function getSSLTime(connectEnd: any, secureConnectionStart: any) {
1377
- let ssl_time: any;
1378
- if (secureConnectionStart) {
1379
- ssl_time = connectEnd - secureConnectionStart;
1380
- }
1381
- return ssl_time;
1382
- }
1383
- return status;
1384
- }
1385
-
1386
- /**
1387
- * EN: Hit probability (1% ~ 100%).
1388
- *
1389
- * ZH: 百分位概率
1390
- *
1391
- * Usage:
1392
- *
1393
- * ```
1394
- * inRate(0.5); // 0.01 ~ 1 true/false
1395
- * ```
1396
- *
1397
- * Output:
1398
- *
1399
- * ```
1400
- * true
1401
- * ```
1402
- *
1403
- * Example: Test the precision.
1404
- *
1405
- * ```
1406
- * // Test
1407
- * let trueCount = 0;
1408
- * let falseCount = 0;
1409
- * new Array(1000000).fill(0).forEach(() => {
1410
- * if (inRate(0.5)) {
1411
- * trueCount++;
1412
- * } else {
1413
- * falseCount++;
1414
- * }
1415
- * });
1416
- * console.log(trueCount, falseCount); // 499994 500006
1417
- * ```
1418
- *
1419
- * @param {number} rate -- 0.1 ~ 1 => 1% ~ 100%
1420
- * @returns {boolean} true 命中
1421
- */
1422
- export function inRate(rate: number): boolean {
1423
- if (Math.random() < rate) {
1424
- return true;
1425
- }
1426
- return false;
1427
- }
1428
-
1429
- /**
1430
- * EN: Determine if it is a secure PWA environment that it can run.
1431
- *
1432
- * ZH: 判断是否是安全的 PWA 环境
1433
- *
1434
- * Usage:
1435
- *
1436
- * ```
1437
- * isSafePWAEnv();
1438
- * ```
1439
- *
1440
- * Output:
1441
- *
1442
- * ```
1443
- * true
1444
- * ```
1445
- *
1446
- * @returns {boolean} true 是
1447
- */
1448
- export function isSafePWAEnv(): boolean {
1449
- // 判断是否支持 async await
1450
- function isSupportAsyncAwait() {
1451
- let isSupportAsyncAwaitFunc;
1452
- try {
1453
- // eval("func = async function(){};");
1454
- const fn = new Function('return async function(){};');
1455
- isSupportAsyncAwaitFunc = fn();
1456
- // console.log('isSupportAsyncAwaitFunc', isSupportAsyncAwaitFunc);
1457
- // 由于async函数的构造器不是全局对象,所以我们需要由下面代码来获取async函数的构造器
1458
- // 具体可以查看以下MDN上有关于AsyncFunction的说明,
1459
- // 地址:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction
1460
- return Object.getPrototypeOf(isSupportAsyncAwaitFunc).constructor != null;
1461
- } catch (e) {
1462
- return false;
1463
- }
1464
- }
1465
- // 判断是否支持 Promise
1466
- function isSupportPromise() {
1467
- if (
1468
- typeof Promise !== 'undefined' &&
1469
- Promise.toString().indexOf('[native code]') !== -1
1470
- ) {
1471
- return true;
1472
- }
1473
- return false;
1474
- }
1475
- // 浏览器信息
1476
- const BrowserType = getBrowserInfo();
1477
- if (
1478
- 'serviceWorker' in navigator &&
1479
- isSupportAsyncAwait() &&
1480
- isSupportPromise() &&
1481
- Boolean(window.fetch) &&
1482
- Boolean(window.indexedDB) &&
1483
- Boolean(window.caches) &&
1484
- !BrowserType['shell']
1485
- ) {
1486
- return true;
1487
- }
1488
- return false;
1489
- }
1490
-
1491
- /**
1492
- * EN: Browser Information
1493
- *
1494
- * ZH: 返回浏览器信息 https://github.com/JowayYoung/juejin-code/blob/master/browser-type.js
1495
- *
1496
- * Usage:
1497
- *
1498
- * ```
1499
- * getBrowserInfo();
1500
- * ```
1501
- *
1502
- * Output:
1503
- *
1504
- * ```
1505
- * {"engine":"webkit","engineVs":"537.36","platform":"desktop","supporter":"chrome","supporterVs":"85.0.4183.121","system":"windows","systemVs":"10"}
1506
- * ```
1507
- *
1508
- * Results:
1509
- *
1510
- * | Index | Field | Description |
1511
- * | --- | --- | --- |
1512
- * | System | system | android, ios, windows, macos, linux |
1513
- * | System version | systemVs | windows: 2000, xp, 2003, vista, 7, 8, 8.1, 10 <br />macos: ... |
1514
- * | Platform | platform | desktop, mobile |
1515
- * | Engine | engine | webkit, gecko, presto, trident |
1516
- * | Engine version | engineVs | - |
1517
- * | Supporter | supporter | edge, opera, chrome, safari, firefox, iexplore |
1518
- * | Supporter version | supporterVs | - |
1519
- * | Shell | shell | (Optional) wechat, qq_browser, qq_app, uc, 360, 2345, sougou, liebao, maxthon, bilibili |
1520
- * | Shell version | shellVs | (Optional) 20/... |
1521
- * | Apple device type | appleType | (Optional) ipad, iphone, ipod, iwatch |
1522
- *
1523
- * Example: Determine the environment of the mobile QQ.
1524
- *
1525
- * ```
1526
- * const { system, shell } = getBrowserInfo();
1527
- * const isMobileQQ = ['android', 'ios'].includes(system) && ['qq_browser', 'qq_app'].includes(shell);
1528
- * ```
1529
- *
1530
- * @returns 浏览器信息
1531
- * @category Browser Information
1532
- */
1533
- export function getBrowserInfo(): {
1534
- engine: string; // webkit gecko presto trident
1535
- engineVs: string;
1536
- platform: string; // desktop mobile
1537
- supporter: string; // chrome safari firefox opera iexplore edge
1538
- supporterVs: string;
1539
- system: string; // windows macos linux android ios
1540
- systemVs: string;
1541
- shell?: string; // wechat qq uc 360 2345 sougou liebao maxthon
1542
- shellVs?: string;
1543
- appleType?: string;
1544
- } {
1545
- try {
1546
- // 权重:系统 + 系统版本 > 平台 > 内核 + 载体 + 内核版本 + 载体版本 > 外壳 + 外壳版本
1547
- const ua: string = navigator.userAgent.toLowerCase();
1548
- const testUa: (regexp: RegExp) => boolean = regexp => regexp.test(ua);
1549
- const testVs: (regexp: RegExp) => string = regexp => {
1550
- const matchRes = ua.match(regexp);
1551
- let ret = '';
1552
- if (matchRes) {
1553
- ret = matchRes
1554
- .toString()
1555
- .replace(/[^0-9|_.]/g, '')
1556
- .replace(/_/g, '.');
1557
- }
1558
- return ret;
1559
- };
1560
- // 系统
1561
- let system = '';
1562
- // Apple device type.
1563
- let appleType = '';
1564
- if (testUa(/windows|win32|win64|wow32|wow64/g)) {
1565
- system = 'windows'; // windows系统
1566
- } else if (testUa(/macintosh|macintel/g)) {
1567
- system = 'macos'; // macos系统
1568
- } else if (testUa(/x11/g)) {
1569
- system = 'linux'; // linux系统
1570
- } else if (testUa(/android|adr/g)) {
1571
- system = 'android'; // android系统
1572
- } else if (testUa(/ios|iphone|ipad|ipod|iwatch/g)) {
1573
- system = 'ios'; // ios系统
1574
- if (testUa(/ipad/g)) {
1575
- appleType = 'ipad';
1576
- } else if (testUa(/iphone/g)) {
1577
- appleType = 'iphone';
1578
- } else if (testUa(/iwatch/g)) {
1579
- appleType = 'iwatch';
1580
- } else if (testUa(/ipod/g)) {
1581
- appleType = 'ipod';
1582
- }
1583
- }
1584
- // 系统版本
1585
- let systemVs = '';
1586
- if (system === 'windows') {
1587
- if (testUa(/windows nt 5.0|windows 2000/g)) {
1588
- systemVs = '2000';
1589
- } else if (testUa(/windows nt 5.1|windows xp/g)) {
1590
- systemVs = 'xp';
1591
- } else if (testUa(/windows nt 5.2|windows 2003/g)) {
1592
- systemVs = '2003';
1593
- } else if (testUa(/windows nt 6.0|windows vista/g)) {
1594
- systemVs = 'vista';
1595
- } else if (testUa(/windows nt 6.1|windows 7/g)) {
1596
- systemVs = '7';
1597
- } else if (testUa(/windows nt 6.2|windows 8/g)) {
1598
- systemVs = '8';
1599
- } else if (testUa(/windows nt 6.3|windows 8.1/g)) {
1600
- systemVs = '8.1';
1601
- } else if (testUa(/windows nt 10.0|windows 10/g)) {
1602
- systemVs = '10';
1603
- }
1604
- } else if (system === 'macos') {
1605
- systemVs = testVs(/os x [\d._]+/g);
1606
- } else if (system === 'android') {
1607
- systemVs = testVs(/android [\d._]+/g);
1608
- } else if (system === 'ios') {
1609
- systemVs = testVs(/os [\d._]+/g);
1610
- }
1611
- // 平台
1612
- let platform = '';
1613
- if (system === 'windows' || system === 'macos' || system === 'linux') {
1614
- platform = 'desktop'; // 桌面端
1615
- } else if (system === 'android' || system === 'ios' || testUa(/mobile/g)) {
1616
- platform = 'mobile'; // 移动端
1617
- }
1618
- // 内核和载体
1619
- let engine = '';
1620
- let supporter = '';
1621
- if (testUa(/applewebkit/g)) {
1622
- engine = 'webkit'; // webkit内核
1623
- if (testUa(/edge/g)) {
1624
- supporter = 'edge'; // edge浏览器
1625
- } else if (testUa(/opr/g)) {
1626
- supporter = 'opera'; // opera浏览器
1627
- } else if (testUa(/chrome/g)) {
1628
- supporter = 'chrome'; // chrome浏览器
1629
- } else if (testUa(/safari/g)) {
1630
- supporter = 'safari'; // safari浏览器
1631
- }
1632
- } else if (testUa(/gecko/g) && testUa(/firefox/g)) {
1633
- engine = 'gecko'; // gecko内核
1634
- supporter = 'firefox'; // firefox浏览器
1635
- } else if (testUa(/presto/g)) {
1636
- engine = 'presto'; // presto内核
1637
- supporter = 'opera'; // opera浏览器
1638
- } else if (testUa(/trident|compatible|msie/g)) {
1639
- engine = 'trident'; // trident内核
1640
- supporter = 'iexplore'; // iexplore浏览器
1641
- }
1642
- // 内核版本
1643
- let engineVs = '';
1644
- if (engine === 'webkit') {
1645
- engineVs = testVs(/applewebkit\/[\d._]+/g);
1646
- } else if (engine === 'gecko') {
1647
- engineVs = testVs(/gecko\/[\d._]+/g);
1648
- } else if (engine === 'presto') {
1649
- engineVs = testVs(/presto\/[\d._]+/g);
1650
- } else if (engine === 'trident') {
1651
- engineVs = testVs(/trident\/[\d._]+/g);
1652
- }
1653
- // 载体版本
1654
- let supporterVs = '';
1655
- if (supporter === 'chrome') {
1656
- supporterVs = testVs(/chrome\/[\d._]+/g);
1657
- } else if (supporter === 'safari') {
1658
- supporterVs = testVs(/version\/[\d._]+/g);
1659
- } else if (supporter === 'firefox') {
1660
- supporterVs = testVs(/firefox\/[\d._]+/g);
1661
- } else if (supporter === 'opera') {
1662
- supporterVs = testVs(/opr\/[\d._]+/g);
1663
- } else if (supporter === 'iexplore') {
1664
- supporterVs = testVs(/(msie [\d._]+)|(rv:[\d._]+)/g);
1665
- } else if (supporter === 'edge') {
1666
- supporterVs = testVs(/edge\/[\d._]+/g);
1667
- }
1668
- // 外壳和外壳版本
1669
- let shell = '';
1670
- let shellVs = '';
1671
- if (testUa(/micromessenger/g)) {
1672
- shell = 'wechat'; // 微信浏览器
1673
- shellVs = testVs(/micromessenger\/[\d._]+/g);
1674
- } else if (testUa(/qqbrowser/g)) {
1675
- shell = 'qq_browser'; // QQ Browser
1676
- shellVs = testVs(/qqbrowser\/[\d._]+/g);
1677
- } else if (testUa(/\sqq/g)) {
1678
- shell = 'qq_app'; // QQ APP
1679
- } else if (testUa(/ucbrowser/g)) {
1680
- shell = 'uc'; // UC浏览器
1681
- shellVs = testVs(/ucbrowser\/[\d._]+/g);
1682
- } else if (testUa(/qihu 360se/g)) {
1683
- shell = '360'; // 360浏览器(无版本)
1684
- } else if (testUa(/2345explorer/g)) {
1685
- shell = '2345'; // 2345浏览器
1686
- shellVs = testVs(/2345explorer\/[\d._]+/g);
1687
- } else if (testUa(/metasr/g)) {
1688
- shell = 'sougou'; // 搜狗浏览器(无版本)
1689
- } else if (testUa(/lbbrowser/g)) {
1690
- shell = 'liebao'; // 猎豹浏览器(无版本)
1691
- } else if (testUa(/maxthon/g)) {
1692
- shell = 'maxthon'; // 遨游浏览器
1693
- shellVs = testVs(/maxthon\/[\d._]+/g);
1694
- } else if (testUa(/biliapp/g)) {
1695
- shell = 'bilibili'; // 哔哩哔哩
1696
- }
1697
- return Object.assign(
1698
- {
1699
- engine, // webkit gecko presto trident
1700
- engineVs,
1701
- platform, // desktop mobile
1702
- supporter, // chrome safari firefox opera iexplore edge
1703
- supporterVs,
1704
- system, // windows macos linux android ios
1705
- systemVs
1706
- },
1707
- {
1708
- shell, // wechat qq uc 360 2345 sougou liebao maxthon
1709
- shellVs,
1710
- appleType
1711
- }
1712
- );
1713
- } catch (err) {
1714
- console.warn('mazey:', err);
1715
- return {
1716
- engine: '', // webkit gecko presto trident
1717
- engineVs: '',
1718
- platform: '', // desktop mobile
1719
- supporter: '', // chrome safari firefox opera iexplore edge
1720
- supporterVs: '',
1721
- system: '', // windows macos linux android ios
1722
- systemVs: ''
1723
- };
1724
- }
1725
- }
1726
-
1727
- /**
1728
- * @method clearHtml
1729
- * @description 去除HTML标签
1730
- * @param {string} str 带html标签的字符串
1731
- * @returns {string} 字符串
1732
- */
1733
- export function clearHtml(str: string): string {
1734
- return str.replace(/<\/?.+?>/g, '').replace(/[\r\n]/g, '');
1735
- }
1736
-
1737
- /**
1738
- * @method cutCHSString
1739
- * @description 截取字符串,中文算2个字节
1740
- * @param {string} str 要截取的字符串
1741
- * @param {number} len
1742
- * @param {boolean} hasDot
1743
- * @returnss {string} 返回截取后的字符串
1744
- */
1745
- export function cutCHSString(str: string, len: number, hasDot = false): string {
1746
- if (str == '' || !str) {
1747
- return '';
1748
- } else {
1749
- let newLength = 0;
1750
- let newStr = '';
1751
- // eslint-disable-next-line no-control-regex
1752
- const chineseRegex = /[^\x00-\xff]/g;
1753
- let singleChar = '';
1754
- const strLength = str.replace(chineseRegex, '**').length;
1755
- for (let i = 0; i < strLength; i++) {
1756
- singleChar = str.charAt(i).toString();
1757
- if (singleChar.match(chineseRegex) != null) {
1758
- newLength += 2;
1759
- } else {
1760
- newLength++;
1761
- }
1762
- if (newLength > len) {
1763
- break;
1764
- }
1765
- newStr += singleChar;
1766
- }
1767
-
1768
- if (hasDot && strLength > len) {
1769
- newStr += '...';
1770
- }
1771
- return newStr;
1772
- }
1773
- }
1774
-
1775
- /**
1776
- * EN: Check whether the page is loaded successfully (Keepe the compatibility in case that browser's `load` event has been triggered).
1777
- *
1778
- * ZH: 页面加载完成
1779
- *
1780
- * ```
1781
- * windowLoaded(30) // second
1782
- * .then(res => {
1783
- * console.log(`Load Success: ${res}`); // Load Success: load
1784
- * })
1785
- * .catch(err => {
1786
- * console.log(`Load Timeout or Fail: ${err.message}`);
1787
- * });
1788
- * ```
1789
- *
1790
- * @param {number} timeout 超时时间 / 单位:秒
1791
- * @returns {Promise<string>} document is loaded? 'complete' 'load' / 'timeout'
1792
- * @category Load Resource
1793
- */
1794
- export function windowLoaded(timeout = 90): Promise<string | Error> {
1795
- let loaded: (value: string) => void = () => undefined;
1796
- let loadFail: (value: Error) => void;
1797
- const status = new Promise(
1798
- (resolve: (value: string) => void, reject: (value: Error) => void) => {
1799
- loaded = resolve;
1800
- loadFail = reject;
1801
- }
1802
- );
1803
- if (document.readyState === 'complete') {
1804
- loaded('complete');
1805
- } else {
1806
- window.addEventListener('load', () => loaded('load'));
1807
- }
1808
- // 超过 timeout 秒后加载失败
1809
- setTimeout(() => loadFail(Error('timeout')), timeout * 1000);
1810
- return status;
1811
- }
1812
-
1813
- /**
1814
- * EN: Add `<style>` in `<head>`.
1815
- *
1816
- * ZH: 添加样式标签; style: 样式标签内的字符串; id: `<style>` 标签的 `id`; 返回: 添加成功/失败.
1817
- *
1818
- * Example 1: Add the `<style>` with `id`, and repeated invoking will update the content instead of adding a new one.
1819
- *
1820
- * ```
1821
- * addStyle(
1822
- * `
1823
- * body {
1824
- * background-color: #333;
1825
- * }
1826
- * `,
1827
- * {
1828
- * id: 'test',
1829
- * }
1830
- * );
1831
- * // <style id="test">
1832
- * // body {
1833
- * // background-color: #333;
1834
- * // }
1835
- * // </style>
1836
- * ```
1837
- *
1838
- * Example 2: Add the `<style>` without `id`, and repeated invoking will adding a new one.
1839
- *
1840
- * ```
1841
- * addStyle(
1842
- * `
1843
- * body {
1844
- * background-color: #333;
1845
- * }
1846
- * `
1847
- * );
1848
- * // <style>
1849
- * // body {
1850
- * // background-color: #333;
1851
- * // }
1852
- * // </style>
1853
- * ```
1854
- *
1855
- * @param style Style string.
1856
- * @param options.id `id` in `<style>`
1857
- * @returns Success/Fail
1858
- */
1859
- export function addStyle(
1860
- style: string,
1861
- options: { id?: string } = { id: '' }
1862
- ): boolean {
1863
- // console.log('_ style', style);
1864
- // console.log('_ options', options);
1865
- if (!style) {
1866
- return false;
1867
- }
1868
- // 创建 style 文档碎片
1869
- const styleFrag = document.createDocumentFragment();
1870
- let idDom: HTMLElement | null = null;
1871
- let domId = '';
1872
- // Custom Style
1873
- const customStyle = document.createElement('style');
1874
- // 如果需要 ID
1875
- if (options.id) {
1876
- domId = `${options.id}`;
1877
- idDom = document.getElementById(domId);
1878
- // 如果 Dom 不存在,插入 style
1879
- if (!idDom) {
1880
- customStyle.setAttribute('id', options.id);
1881
- customStyle.innerHTML = style;
1882
- styleFrag.appendChild(customStyle);
1883
- document.head.appendChild(styleFrag);
1884
- } else {
1885
- // 如果 Dom 存在,直接更新
1886
- idDom.innerHTML = style;
1887
- }
1888
- } else {
1889
- // 不需要 ID,直接添加新标签
1890
- customStyle.innerHTML = style;
1891
- styleFrag.appendChild(customStyle);
1892
- document.head.appendChild(styleFrag);
1893
- }
1894
- return true;
1895
- }
1896
-
1897
- /**
1898
- * EN: Custom console printing (`console`).
1899
- *
1900
- * ZH: 生成自定义控制台打印
1901
- *
1902
- * Usage:
1903
- *
1904
- * ```
1905
- * const myConsole = genCustomConsole('MazeyLog:');
1906
- * myConsole.log('I am string.');
1907
- * myConsole.info('I am boolean.', true);
1908
- * myConsole.info('I am number.', 123, 456);
1909
- * myConsole.info('I am object.', { a: 123, b: 456});
1910
- * ```
1911
- *
1912
- * Output:
1913
- *
1914
- * ```
1915
- * MazeyLog: I am string.
1916
- * MazeyLog: I am boolean. true
1917
- * MazeyLog: I am number. 123 456
1918
- * MazeyLog: I am object. {a: 123, b: 456}
1919
- * ```
1920
- *
1921
- * @param {string} prefix 前缀
1922
- * @param {string} locales A locale string.
1923
- * @param {function} logFn The function with Log.
1924
- * @param {function} errorFn The function with Error.
1925
- * @returns {object} 新实例
1926
- */
1927
- export function genCustomConsole(
1928
- prefix = '',
1929
- options: {
1930
- isClosed?: boolean;
1931
- showWrap?: boolean;
1932
- showDate?: boolean;
1933
- locales?: string;
1934
- logFn?: () => void;
1935
- errorFn?: () => void;
1936
- } = {
1937
- isClosed: false,
1938
- showWrap: false,
1939
- showDate: false,
1940
- locales: 'en-US',
1941
- logFn: () => undefined,
1942
- errorFn: () => undefined
1943
- }
1944
- ): Console {
1945
- const {
1946
- isClosed,
1947
- showWrap,
1948
- showDate,
1949
- locales,
1950
- logFn,
1951
- errorFn
1952
- } = Object.assign(
1953
- {
1954
- isClosed: false,
1955
- showWrap: false,
1956
- showDate: false,
1957
- locales: 'en-US',
1958
- logFn: () => undefined,
1959
- errorFn: () => undefined
1960
- },
1961
- options
1962
- );
1963
- const methods = ['log', 'info', 'warn', 'error'];
1964
- const newConsole = Object.create(null);
1965
- // https://stackoverflow.com/questions/3552461/how-do-i-format-a-date-in-javascript
1966
- const formatDate = () => {
1967
- const dateOptions: Intl.DateTimeFormatOptions = {
1968
- weekday: 'short',
1969
- year: 'numeric',
1970
- month: 'short',
1971
- day: 'numeric',
1972
- hour: 'numeric',
1973
- // hourCycle: 'h24',
1974
- minute: 'numeric',
1975
- second: 'numeric'
1976
- };
1977
- const todayDateIns = new Date();
1978
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
1979
- // https://datatracker.ietf.org/doc/html/rfc4647
1980
- const dateStr = todayDateIns.toLocaleDateString(locales, dateOptions);
1981
- return dateStr;
1982
- };
1983
- // if (showDate) {
1984
- // prefix = `${dateStr} ${prefix}`;
1985
- // }
1986
- methods.forEach(method => {
1987
- newConsole[method] = function(...argu: any) {
1988
- if (isClosed) {
1989
- return false;
1990
- }
1991
- let elaboratePrefix = prefix;
1992
- let datePrefix = prefix;
1993
- if (typeof prefix === 'string' && prefix.length >= 2) {
1994
- const len = prefix.length;
1995
- if (prefix[len - 1] === ':') {
1996
- elaboratePrefix = prefix.substring(0, len - 1);
1997
- } else {
1998
- elaboratePrefix = prefix;
1999
- }
2000
- }
2001
- if (showWrap) {
2002
- console.log(`--- ${elaboratePrefix} - begin ---`);
2003
- }
2004
- if (showDate) {
2005
- if (prefix) {
2006
- datePrefix = `${formatDate()} ${prefix}`;
2007
- } else {
2008
- datePrefix = `${formatDate()}`;
2009
- }
2010
- }
2011
- if (prefix || showDate) {
2012
- (console as any)[method](datePrefix, ...argu);
2013
- } else {
2014
- (console as any)[method](...argu);
2015
- }
2016
- if (method === 'log') {
2017
- logFn();
2018
- }
2019
- if (method === 'error') {
2020
- errorFn();
2021
- }
2022
- if (showWrap) {
2023
- console.log(`--- ${elaboratePrefix} - end ---`);
2024
- }
2025
- };
2026
- });
2027
- return newConsole;
2028
- }
2029
-
2030
- /**
2031
- * Verify the validity of axios response.
2032
- *
2033
- * Reference: [Handling Errors](https://axios-http.com/docs/handling_errors)
2034
- */
2035
- export function zAxiosIsValidRes(
2036
- res: any,
2037
- options: {
2038
- validStatusRange?: number[];
2039
- validCode?: number[];
2040
- } = {
2041
- validStatusRange: [200, 300],
2042
- validCode: [0]
2043
- }
2044
- ): boolean {
2045
- const { validStatusRange, validCode } = Object.assign(
2046
- {
2047
- validStatusRange: [200, 300],
2048
- validCode: [0]
2049
- },
2050
- options
2051
- );
2052
- if (validStatusRange.length !== 2) {
2053
- console.error('valid validStatusRange is required');
2054
- }
2055
- let ret = false;
2056
- if (
2057
- res &&
2058
- res.status &&
2059
- validStatusRange.length === 2 &&
2060
- res.status >= validStatusRange[0] &&
2061
- res.status < validStatusRange[1]
2062
- ) {
2063
- const resData = res.data;
2064
- if (resData && validCode.includes(resData.code)) {
2065
- ret = true;
2066
- }
2067
- }
2068
- return ret;
2069
- }
2070
-
2071
- /**
2072
- * Verify the validity of a non-empty array.
2073
- */
2074
- export function isNonEmptyArray(arr: any[]): boolean {
2075
- let ret = false;
2076
- if (Array.isArray(arr) && arr.length) {
2077
- ret = true;
2078
- }
2079
- return ret;
2080
- }
2081
-
2082
- /**
2083
- * Determine the validity of the data.
2084
- *
2085
- * Usage:
2086
- *
2087
- * ```
2088
- * const validData = {
2089
- * a: {
2090
- * b: {
2091
- * c: 413
2092
- * }
2093
- * }
2094
- * };
2095
- *
2096
- * const isValidDataResA = isValidData(validData, ['a', 'b', 'c'], 2333);
2097
- * const isValidDataResB = isValidData(validData, ['a', 'b', 'c'], 413);
2098
- * const isValidDataResC = isValidData(validData, ['d', 'd'], 413);
2099
- *
2100
- * console.log('isValidDataResA:', isValidDataResA);
2101
- * console.log('isValidDataResB:', isValidDataResB);
2102
- * console.log('isValidDataResC:', isValidDataResC);
2103
- * ```
2104
- *
2105
- * Output:
2106
- *
2107
- * ```
2108
- * isValidDataResA: false
2109
- * isValidDataResB: true
2110
- * isValidDataResC: false
2111
- * ```
2112
- *
2113
- * @param {any} data Original Data
2114
- * @param {string[]} attributes Data Attributes
2115
- * @param {any} validValue Given Value for verifying.
2116
- * @returns {boolean} Return TRUE if the data is valid.
2117
- */
2118
- export function isValidData(
2119
- data: any,
2120
- attributes: string[],
2121
- validValue: any
2122
- ): boolean {
2123
- let ret = false;
2124
- const foundRet = attributes.reduce((foundValue, curr) => {
2125
- if (foundValue[curr]) {
2126
- foundValue = foundValue[curr];
2127
- } else {
2128
- return Object.create(null);
2129
- }
2130
- // console.log('foundValue', foundValue);
2131
- return foundValue;
2132
- }, data);
2133
- // console.log('foundRet', foundRet);
2134
- if (foundRet === validValue) {
2135
- ret = true;
2136
- }
2137
- return ret;
2138
- }
2139
-
2140
- /**
2141
- * 语义化文件大小, 把字节转换成正常文件大小.
2142
- */
2143
- export function getFileSize(size: number): string {
2144
- const toCeilStr: (v: number) => string = n => String(Math.ceil(n));
2145
- if (!size) return '';
2146
- const num = 1024.0; // byte
2147
- if (size < num) {
2148
- return size + ' B';
2149
- }
2150
- if (size < Math.pow(num, 2)) {
2151
- return toCeilStr(size / num) + ' KB';
2152
- } // kb
2153
- if (size < Math.pow(num, 3)) {
2154
- return toCeilStr(size / Math.pow(num, 2)) + ' MB';
2155
- } // M
2156
- if (size < Math.pow(num, 4)) {
2157
- return toCeilStr(size / Math.pow(num, 3)) + ' G';
2158
- } // G
2159
- return toCeilStr(size / Math.pow(num, 4)) + ' T';
2160
- }
2161
-
2162
- /**
2163
- * Detect webp support.
2164
- *
2165
- * Reference: [Detect WEBP Support with JavaScript](https://davidwalsh.name/detect-webp)
2166
- */
2167
- export function isSupportWebp(): Promise<boolean> {
2168
- const fn = (resolve: (v: boolean) => void) => {
2169
- const img = new Image();
2170
- img.onload = () => {
2171
- resolve(img.width > 0 && img.height > 0);
2172
- };
2173
- img.onerror = () => {
2174
- resolve(false);
2175
- };
2176
- img.src =
2177
- 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=';
2178
- };
2179
- return new Promise(fn);
2180
- }
2181
-
2182
- /**
2183
- * Generate a Hash Code from a string.
2184
- *
2185
- * Reference: [Generate a Hash from string in Javascript](https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery)
2186
- */
2187
- export function genHashCode(str: string): number {
2188
- let hash = 0,
2189
- i,
2190
- chr;
2191
- for (i = 0; i < str.length; i++) {
2192
- chr = str.charCodeAt(i);
2193
- hash = (hash << 5) - hash + chr;
2194
- hash |= 0;
2195
- }
2196
- return hash;
2197
- }
2198
-
2199
- /**
2200
- * Return the formatted date string in the given format.
2201
- *
2202
- * Usage:
2203
- *
2204
- * ```
2205
- * console.log('Default formatDate value:', formatDate());
2206
- * console.log('String formatDate value:', formatDate('Tue Jan 11 2022 14:12:26 GMT+0800 (China Standard Time)', 'yyyy-MM-dd hh:mm:ss'));
2207
- * console.log('Number formatDate value:', formatDate(1641881235000, 'yyyy-MM-dd hh:mm:ss'));
2208
- * console.log('Date formatDate value:', formatDate(new Date(2014, 1, 11), 'MM/dd/yyyy'));
2209
- * ```
2210
- *
2211
- * Output:
2212
- *
2213
- * ```
2214
- * Default formatDate value: 2023-01-11
2215
- * String formatDate value: 2022-01-11 14:12:26
2216
- * Number formatDate value: 2022-01-11 14:07:15
2217
- * Date formatDate value: 02/11/2014
2218
- * ```
2219
- *
2220
- * @param {Date|number|string} dateIns Original Date
2221
- * @param {string} format Format String
2222
- * @returns {string} Return the formatted date string.
2223
- */
2224
- export function formatDate(
2225
- dateIns?: Date | number | string,
2226
- format = 'yyyy-MM-dd'
2227
- ): string {
2228
- if (!dateIns) {
2229
- dateIns = new Date();
2230
- }
2231
- const tempDate = new Date(dateIns);
2232
- const o: {
2233
- [key: string]: string | number;
2234
- } = {
2235
- yyyy: tempDate.getFullYear(),
2236
- MM: tempDate.getMonth() + 1,
2237
- dd: tempDate.getDate(),
2238
- hh:
2239
- tempDate.getHours() < 10
2240
- ? '0' + tempDate.getHours()
2241
- : tempDate.getHours(),
2242
- mm:
2243
- tempDate.getMinutes() < 10
2244
- ? '0' + tempDate.getMinutes()
2245
- : tempDate.getMinutes(),
2246
- ss:
2247
- tempDate.getSeconds() < 10
2248
- ? '0' + tempDate.getSeconds()
2249
- : tempDate.getSeconds()
2250
- };
2251
- let tempFormat = format || 'yyyy-MM-dd';
2252
- Object.keys(o).forEach(key => {
2253
- let value = o[key];
2254
- if (key === 'MM' && Number(value) <= 9) {
2255
- value = `0${value}`;
2256
- }
2257
- tempFormat = tempFormat.replace(key, String(value));
2258
- });
2259
- return tempFormat;
2260
- }