mazey 3.11.6 → 3.12.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/README.md CHANGED
@@ -1,991 +1,991 @@
1
- English | [简体中文](https://github.com/mazeyqian/mazey/blob/main/README_ZH.md)
2
-
3
- # Mazey
4
-
5
- [![NPM version][npm-image]][npm-url]
6
- [![l][l-image]][l-url]
7
-
8
- [npm-image]: https://img.shields.io/npm/v/mazey
9
- [npm-url]: https://npmjs.org/package/mazey
10
- [l-image]: https://img.shields.io/npm/l/mazey
11
- [l-url]: https://github.com/mazeyqian/mazey
12
-
13
- Mazey is a functional library for daily front-end work. There are already many excellent libraries for front-end development, but creating a file named `utils.js` or `common.js` is generally used to supply common functions in projects. It's boring to copy similar functions across multiple projects. That's why I've created this library and will keep updating it to serve as a reliable resource for front-end needs.
14
-
15
- ## Install
16
-
17
- Use Mazey via [npm](https://www.npmjs.com/package/mazey).
18
-
19
- ```shell
20
- npm install mazey --save
21
- ```
22
-
23
- Use Mazey from CDN.
24
-
25
- ```html
26
- <script type="text/javascript" src="//i.mazey.net/mazey/lib/mazey.min.js"></script>
27
- ```
28
-
29
- Of course, you can also download this file and serve it yourself. The file locates at the `lib/mazey.min.js`.
30
-
31
- ## Usage
32
-
33
- Example: Use a function to load JavaScript script.
34
-
35
- Import from [npm](https://www.npmjs.com/package/mazey).
36
-
37
- ```javascript
38
- import { isNumber } from 'mazey';
39
-
40
- const x = Infinity;
41
- isNumber(x); // <=> typeof x === 'string' && !isNaN(x) && isFinite(x)
42
- // Output: false
43
- ```
44
-
45
- Import from CDN.
46
-
47
- ```html
48
- <script type="text/javascript" src="//i.mazey.net/mazey/lib/mazey.min.js"></script>
49
- <script>
50
- const x = Infinity;
51
- mazey.isNumber(x, { isInfinityAsNumber: true }); // <=> typeof x === 'string' && !isNaN(x)
52
- // Output: true
53
- </script>
54
- ```
55
-
56
- ## API Examples
57
-
58
- There are some examples maintained by hand below. For more information, please check the [full documentation](https://mazey.cn/t/m).
59
-
60
- ### Table of Contents
61
-
62
- <!-- toc - begin -->
63
- - Generated with ❤️
64
- - [Load Resource](#load-resource)
65
- - [loadScript](#loadscript)
66
- - [loadScriptIfUndefined](#loadscriptifundefined)
67
- - [loadCSS](#loadcss)
68
- - [loadImage](#loadimage)
69
- - [windowLoaded](#windowloaded)
70
- - [Util](#util)
71
- - [isNumber](#isnumber)
72
- - [isJSONString](#isjsonstring)
73
- - [isValidData](#isvaliddata)
74
- - [genRndNumString](#genrndnumstring)
75
- - [formatDate](#formatdate)
76
- - [debounce](#debounce)
77
- - [throttle](#throttle)
78
- - [convertCamelToKebab](#convertcameltokebab)
79
- - [convertCamelToUnder](#convertcameltounder)
80
- - [deepCopy](#deepcopy)
81
- - [URL](#url)
82
- - [getQueryParam](#getqueryparam)
83
- - [getUrlParam](#geturlparam)
84
- - [getHashQueryParam](#gethashqueryparam)
85
- - [getDomain](#getdomain)
86
- - [updateQueryParam](#updatequeryparam)
87
- - [isValidUrl](#isvalidurl)
88
- - [isValidHttpUrl](#isvalidhttpurl)
89
- - [Cache Data](#cache-data)
90
- - [Cookie](#cookie)
91
- - [Storage](#storage)
92
- - [DOM](#dom)
93
- - [addStyle](#addstyle)
94
- - [Class](#class)
95
- - [newLine](#newline)
96
- - [Calculate and Formula](#calculate-and-formula)
97
- - [inRate](#inrate)
98
- - [longestComSubstring](#longestcomsubstring)
99
- - [longestComSubsequence](#longestcomsubsequence)
100
- - [Browser Information](#browser-information)
101
- - [getBrowserInfo](#getbrowserinfo)
102
- - [isSafePWAEnv](#issafepwaenv)
103
- - [Web Performance](#web-performance)
104
- - [getPerformance](#getperformance)
105
- - [Debug](#debug)
106
- - [genCustomConsole](#gencustomconsole)
107
- <!-- toc - end -->
108
-
109
- ### Load Resource
110
-
111
- #### loadScript
112
-
113
- Load a JavaScript file from the server and execute it.
114
-
115
- Usage:
116
-
117
- ```javascript
118
- loadScript(
119
- 'http://example.com/static/js/plugin-2.1.1.min.js',
120
- {
121
- id: 'iamid', // (Optional) script ID, default none
122
- timeout: 5000, // (Optional) timeout, default `5000`
123
- isDefer: false, // (Optional) defer, default `false`
124
- }
125
- )
126
- .then(
127
- res => {
128
- console.log(`Load JavaScript script: ${res}`);
129
- }
130
- )
131
- .catch(
132
- err => {
133
- console.error(`Load JavaScript script: ${err.message}`)
134
- }
135
- );
136
- ```
137
-
138
- Output:
139
-
140
- ```text
141
- Load JavaScript script: loaded
142
- ```
143
-
144
- #### loadScriptIfUndefined
145
-
146
- Load a script from the given URL if it (`window['attribute']`) has not already been loaded.
147
-
148
- Usage:
149
-
150
- ```javascript
151
- loadScriptIfUndefined('xyz', 'https://example.com/lib/xyz.min.js')
152
- .then(() => {
153
- console.log('xyz is loaded.');
154
- })
155
- .catch(err => {
156
- console.log('Failed to load xyz.', err);
157
- });
158
- ```
159
-
160
- Output:
161
-
162
- ```text
163
- xyz is loaded.
164
- ```
165
-
166
- #### loadCSS
167
-
168
- Load a CSS file from the server.
169
-
170
- Usage:
171
-
172
- ```javascript
173
- loadCSS(
174
- 'http://example.com/path/example.css',
175
- {
176
- id: 'iamid', // Optional, link ID, default none
177
- }
178
- )
179
- .then(
180
- res => {
181
- console.log(`Load CSS Success: ${res}`);
182
- }
183
- )
184
- .catch(
185
- err => {
186
- console.error(`Load CSS Fail: ${err.message}`)
187
- }
188
- );
189
- ```
190
-
191
- Output:
192
-
193
- ```text
194
- Load CSS Success: loaded
195
- ```
196
-
197
- #### loadImage
198
-
199
- Load an image from the given URL.
200
-
201
- The target image will be loaded in the background, and the Promise status will change after the image is loaded. If the image fails to load, the Promise status will change to `reject` with the error object. If the image is loaded successfully, the Promise status will change to `resolve` with the image object. This method can be used to preload images and cache them in the browser. It can also be used to implement lazy loading of images.
202
-
203
- Note that this method will not add the image to the DOM.
204
-
205
- Usage:
206
-
207
- ```javascript
208
- loadImage('https://example.com/example.png')
209
- .then((img) => {
210
- console.log(img);
211
- })
212
- .catch((err) => {
213
- console.log(err);
214
- });
215
- ```
216
-
217
- #### windowLoaded
218
-
219
- Check whether the page is loaded successfully (Keep the compatibility if the browser's `load` event has been triggered).
220
-
221
- Usage:
222
-
223
- ```javascript
224
- windowLoaded(30) // second
225
- .then(res => {
226
- console.log(`Load Success: ${res}`);
227
- })
228
- .catch(err => {
229
- console.log(`Load Timeout or Fail: ${err.message}`);
230
- });
231
- ```
232
-
233
- Output:
234
-
235
- ```text
236
- Load Success: load
237
- ```
238
-
239
- ### Util
240
-
241
- #### isNumber
242
-
243
- Check whether it is a right number.
244
-
245
- Usage:
246
-
247
- ```javascript
248
- const ret1 = isNumber(123);
249
- const ret2 = isNumber('123');
250
- // Default: NaN, Infinity is not Number
251
- const ret3 = isNumber(Infinity);
252
- const ret4 = isNumber(Infinity, { isInfinityAsNumber: true });
253
- const ret5 = isNumber(NaN);
254
- const ret6 = isNumber(NaN, { isNaNAsNumber: true, isInfinityAsNumber: true });
255
- console.log(ret1, ret2, ret3, ret4, ret5, ret6);
256
- ```
257
-
258
- Output:
259
-
260
- ```text
261
- true false false true false true
262
- ```
263
-
264
- #### isJSONString
265
-
266
- Check whether it is a valid JSON string.
267
-
268
- Usage:
269
-
270
- ```javascript
271
- const ret1 = isJSONString(`['a', 'b', 'c']`);
272
- const ret2 = isJSONString(`["a", "b", "c"]`);
273
- console.log(ret1);
274
- console.log(ret2);
275
- ```
276
-
277
- Output:
278
-
279
- ```text
280
- false
281
- true
282
- ```
283
-
284
- #### isValidData
285
-
286
- Determine the validity of the data.
287
-
288
- Usage:
289
-
290
- ```javascript
291
- const validData = {
292
- a: {
293
- b: {
294
- c: 413
295
- }
296
- }
297
- };
298
-
299
- const isValidDataResA = isValidData(validData, ['a', 'b', 'c'], 2333);
300
- const isValidDataResB = isValidData(validData, ['a', 'b', 'c'], 413);
301
- const isValidDataResC = isValidData(validData, ['d', 'd'], 413);
302
-
303
- console.log('isValidDataResA:', isValidDataResA);
304
- console.log('isValidDataResB:', isValidDataResB);
305
- console.log('isValidDataResC:', isValidDataResC);
306
- ```
307
-
308
- Output:
309
-
310
- ```text
311
- isValidDataResA: false
312
- isValidDataResB: true
313
- isValidDataResC: false
314
- ```
315
-
316
- #### genRndNumString
317
-
318
- Produce a random string of number, `genRndNumString(7)` => '7658495'.
319
-
320
- Usage:
321
-
322
- ```javascript
323
- const ret1 = genRndNumString(4);
324
- const ret2 = genRndNumString(7);
325
- console.log(ret1);
326
- console.log(ret2);
327
- ```
328
-
329
- Output:
330
-
331
- ```text
332
- 9730
333
- 2262490
334
- ```
335
-
336
- #### formatDate
337
-
338
- Return the formatted date string in the given format.
339
-
340
- Usage:
341
-
342
- ```javascript
343
- const ret1 = formatDate();
344
- const ret2 = formatDate('Tue Jan 11 2022 14:12:26 GMT+0800 (China Standard Time)', 'yyyy-MM-dd hh:mm:ss');
345
- const ret3 = formatDate(1641881235000, 'yyyy-MM-dd hh:mm:ss');
346
- const ret4 = formatDate(new Date(2014, 1, 11), 'MM/dd/yyyy');
347
- console.log('Default formatDate value:', ret1);
348
- console.log('String formatDate value:', ret2);
349
- console.log('Number formatDate value:', ret3);
350
- console.log('Date formatDate value:', ret4);
351
- ```
352
-
353
- Output:
354
-
355
- ```text
356
- Default formatDate value: 2023-01-11
357
- String formatDate value: 2022-01-11 14:12:26
358
- Number formatDate value: 2022-01-11 14:07:15
359
- Date formatDate value: 02/11/2014
360
- ```
361
-
362
- #### debounce
363
-
364
- Debounce
365
-
366
- Usage:
367
-
368
- ```javascript
369
- const foo = debounce(() => {
370
- console.log('The debounced function will only be invoked in 1000 milliseconds, the other invoking will disappear during the wait time.');
371
- }, 1000, true);
372
- ```
373
-
374
- #### throttle
375
-
376
- Throttle
377
-
378
- Usage:
379
-
380
- ```javascript
381
- const foo = throttle(() => {
382
- console.log('The function will be invoked at most once per every wait 1000 milliseconds.');
383
- }, 1000, { leading: true });
384
- ```
385
-
386
- Reference: [Lodash](https://lodash.com/docs/4.17.15#throttle)
387
-
388
- #### convertCamelToKebab
389
-
390
- Transfer CamelCase to KebabCase.
391
-
392
- Usage:
393
-
394
- ```javascript
395
- const ret1 = convertCamelToKebab('ABC');
396
- const ret2 = convertCamelToKebab('aBC');
397
- console.log(ret1);
398
- console.log(ret2);
399
- ```
400
-
401
- Output:
402
-
403
- ```text
404
- a-b-c
405
- a-b-c
406
- ```
407
-
408
- #### convertCamelToUnder
409
-
410
- Transfer CamelCase to Underscore.
411
-
412
- Usage:
413
-
414
- ```javascript
415
- const ret1 = convertCamelToUnder('ABC');
416
- const ret2 = convertCamelToUnder('aBC');
417
- console.log(ret1);
418
- console.log(ret2);
419
- ```
420
-
421
- Output:
422
-
423
- ```text
424
- a_b_c
425
- a_b_c
426
- ```
427
-
428
- #### deepCopy
429
-
430
- Copy/Clone Object deeply.
431
-
432
- Usage:
433
-
434
- ```javascript
435
- const ret1 = deepCopy(['a', 'b', 'c']);
436
- const ret2 = deepCopy('abc');
437
- console.log(ret1);
438
- console.log(ret2);
439
- ```
440
-
441
- Output:
442
-
443
- ```text
444
- ['a', 'b', 'c']
445
- abc
446
- ```
447
-
448
- ### URL
449
-
450
- #### getQueryParam
451
-
452
- Get the query param's value of the current Web URL(`location.search`).
453
-
454
- Usage:
455
-
456
- ```javascript
457
- // http://example.com/?t1=1&t2=2&t3=3&t4=4#2333
458
- // ?t1=1&t2=2&t3=3&t4=4
459
- const p1 = getQueryParam('t3');
460
- const p2 = getQueryParam('t4');
461
- console.log(p1, p2);
462
- ```
463
-
464
- Output:
465
-
466
- ```text
467
- 3 4
468
- ```
469
-
470
- #### getUrlParam
471
-
472
- Returns the value of the specified query parameter in the input URL.
473
-
474
- Usage:
475
-
476
- ```javascript
477
- const p1 = getUrlParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't3');
478
- const p2 = getUrlParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't4');
479
- console.log(p1, p2);
480
- ```
481
-
482
- Output:
483
-
484
- ```text
485
- 3 4
486
- ```
487
-
488
- #### getHashQueryParam
489
-
490
- Get the hash query param's value of the current Web URL(`location.hash`).
491
-
492
- Usage:
493
-
494
- ```javascript
495
- // http://example.com/?#2333?t1=1&t2=2&t3=3&t4=4
496
- // #2333?t1=1&t2=2&t3=3&t4=4
497
- const p1 = getHashQueryParam('t3');
498
- const p2 = getHashQueryParam('t4');
499
- console.log(p1, p2);
500
- ```
501
-
502
- Output:
503
-
504
- ```text
505
- 3 4
506
- ```
507
-
508
- #### getDomain
509
-
510
- Get the domain of URL, and other params.
511
-
512
- Usage:
513
-
514
- ```javascript
515
- const ret1 = getDomain('http://example.com/?t1=1&t2=2&t3=3&t4=4');
516
- const ret2 = getDomain('http://example.com/test/thanks?t1=1&t2=2&t3=3&t4=4', ['hostname', 'pathname']);
517
- const ret3 = getDomain('http://example.com:7890/test/thanks', ['hostname']);
518
- const ret4 = getDomain('http://example.com:7890/test/thanks', ['host']); // With Port
519
- const ret5 = getDomain('http://example.com:7890/test/thanks', ['origin']);
520
- const ret6 = getDomain('http://example.com:7890/test/thanks?id=1', ['origin', 'pathname', 'search']);
521
- console.log(ret1);
522
- console.log(ret2);
523
- console.log(ret3);
524
- console.log(ret4);
525
- console.log(ret5);
526
- console.log(ret6);
527
- ```
528
-
529
- Output:
530
-
531
- ```text
532
- example.com
533
- example.com/test/thanks
534
- example.com
535
- example.com:7890
536
- http://example.com:7890
537
- http://example.com:7890/test/thanks?id=1
538
- ```
539
-
540
- #### updateQueryParam
541
-
542
- Update the query param's value of the input URL.
543
-
544
- Usage:
545
-
546
- ```javascript
547
- const ret1 = updateQueryParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't3', 'three');
548
- const ret2 = updateQueryParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't4', 'four');
549
- console.log(ret1);
550
- console.log(ret2);
551
- ```
552
-
553
- Output:
554
-
555
- ```text
556
- http://example.com/?t1=1&t2=2&t3=three&t4=4
557
- http://example.com/?t1=1&t2=2&t3=3&t4=four
558
- ```
559
-
560
- #### isValidUrl
561
-
562
- Checks if the given string is a valid URL, including **scheme URLs**.
563
-
564
- Usage:
565
-
566
- ```javascript
567
- const ret1 = isValidUrl('https://www.example.com');
568
- const ret2 = isValidUrl('http://example.com/path/exx/ss');
569
- const ret3 = isValidUrl('https://www.example.com/?q=hello&age=24#world');
570
- const ret4 = isValidUrl('http://www.example.com/#world?id=9');
571
- const ret5 = isValidUrl('ftp://example.com');
572
- console.log(ret1, ret2, ret3, ret4, ret5);
573
- ```
574
-
575
- Output:
576
-
577
- ```text
578
- true true true true true
579
- ```
580
-
581
- If you are specifically checking for HTTP/HTTPS URLs, it is recommended to use the `isValidHttpUrl` function instead.
582
- The `isValidUrl` function matches all scheme URLs, including FTP and other non-HTTP schemes.
583
-
584
- #### isValidHttpUrl
585
-
586
- Check if the given string is a valid HTTP/HTTPS URL.
587
-
588
- Usage:
589
-
590
- ```javascript
591
- const ret1 = isValidHttpUrl('https://www.example.com');
592
- const ret2 = isValidHttpUrl('http://example.com/path/exx/ss');
593
- const ret3 = isValidHttpUrl('https://www.example.com/?q=hello&age=24#world');
594
- const ret4 = isValidHttpUrl('http://www.example.com/#world?id=9');
595
- const ret5 = isValidHttpUrl('ftp://example.com');
596
- console.log(ret1, ret2, ret3, ret4, ret5);
597
- ```
598
-
599
- Output:
600
-
601
- ```text
602
- true true true true false
603
- ```
604
-
605
- ### Cache Data
606
-
607
- #### Cookie
608
-
609
- Handle Cookie.
610
-
611
- Usage:
612
-
613
- ```javascript
614
- setCookie('test', '123', 30, 'example.com'); // key value day domain
615
- const ret = getCookie('test');
616
- console.log(ret);
617
- ```
618
-
619
- Output:
620
-
621
- ```text
622
- 123
623
- ```
624
-
625
- #### Storage
626
-
627
- Handle Storage (Keep fit for JSON, it can transfer format automatically).
628
-
629
- Usage:
630
-
631
- ```javascript
632
- setSessionStorage('test', '123');
633
- const ret1 = getSessionStorage('test');
634
- setLocalStorage('test', '123');
635
- const ret2 = getLocalStorage('test');
636
- console.log(ret1, ret2);
637
-
638
- // or package in usage
639
- const projectName = 'mazey';
640
- function mSetLocalStorage (key, value) {
641
- return setLocalStorage(`${projectName}_${key}`, value);
642
- }
643
-
644
- function mGetLocalStorage (key) {
645
- return getLocalStorage(`${projectName}_${key}`);
646
- }
647
- ```
648
-
649
- Output:
650
-
651
- ```text
652
- 123 123
653
- ```
654
-
655
- ### DOM
656
-
657
- #### addStyle
658
-
659
- Add `<style>` in `<head>`.
660
-
661
- Example 1: Add the `<style>` with `id`, and repeated invoking will update the content instead of adding a new one.
662
-
663
- ```javascript
664
- addStyle(
665
- `
666
- body {
667
- background-color: #333;
668
- }
669
- `,
670
- {
671
- id: 'test',
672
- }
673
- );
674
- // <style id="test">
675
- // body {
676
- // background-color: #333;
677
- // }
678
- // </style>
679
- ```
680
-
681
- Example 2: Add the `<style>` without `id`, and repeated invoking will add a new one.
682
-
683
- ```javascript
684
- addStyle(
685
- `
686
- body {
687
- background-color: #444;
688
- }
689
- `
690
- );
691
- // <style>
692
- // body {
693
- // background-color: #444;
694
- // }
695
- // </style>
696
- ```
697
-
698
- #### Class
699
-
700
- Modify `class`.
701
-
702
- Usage:
703
-
704
- ```javascript
705
- const dom = document.querySelector('#box');
706
-
707
- // Determine `class`
708
- hasClass(dom, 'test');
709
- // Add `class`
710
- addClass(dom, 'test');
711
- // Remove `class`
712
- removeClass(dom, 'test');
713
- ```
714
-
715
- #### newLine
716
-
717
- Make a new line of HTML.
718
-
719
- Usage:
720
-
721
- ```javascript
722
- const ret1 = newLine('a\nb\nc');
723
- const ret2 = newLine('a\n\nbc');
724
- console.log(ret1);
725
- console.log(ret2);
726
- ```
727
-
728
- Output:
729
-
730
- ```text
731
- a<br />b<br />c
732
- a<br /><br />bc
733
- ```
734
-
735
- ### Calculate and Formula
736
-
737
- #### inRate
738
-
739
- Hit probability (1% ~ 100%).
740
-
741
- Usage:
742
-
743
- ```javascript
744
- const ret = inRate(0.5); // 0.01 ~ 1 true/false
745
- console.log(ret);
746
- ```
747
-
748
- Output:
749
-
750
- ```text
751
- true
752
- ```
753
-
754
- Example: Test the precision.
755
-
756
- ```javascript
757
- // Test
758
- let trueCount = 0;
759
- let falseCount = 0;
760
- new Array(1000000).fill(0).forEach(() => {
761
- if (inRate(0.5)) {
762
- trueCount++;
763
- } else {
764
- falseCount++;
765
- }
766
- });
767
- console.log(trueCount, falseCount); // 499994 500006
768
- ```
769
-
770
- #### longestComSubstring
771
-
772
- Computes the longest common substring of two strings.
773
-
774
- Usage:
775
-
776
- ```javascript
777
- const ret = longestComSubstring('fish', 'finish');
778
- console.log(ret);
779
- ```
780
-
781
- Output:
782
-
783
- ```text
784
- 3
785
- ```
786
-
787
- #### longestComSubsequence
788
-
789
- Computes the longest common subsequence of two strings.
790
-
791
- Usage:
792
-
793
- ```javascript
794
- const ret = longestComSubsequence('fish', 'finish');
795
- console.log(ret);
796
- ```
797
-
798
- Output:
799
-
800
- ```text
801
- 4
802
- ```
803
-
804
- ### Browser Information
805
-
806
- #### getBrowserInfo
807
-
808
- Browser Information
809
-
810
- Usage:
811
-
812
- ```javascript
813
- const ret = getBrowserInfo();
814
- console.log(ret);
815
- ```
816
-
817
- Output:
818
-
819
- ```text
820
- {"engine":"webkit","engineVs":"537.36","platform":"desktop","supporter":"chrome","supporterVs":"85.0.4183.121","system":"windows","systemVs":"10"}
821
- ```
822
-
823
- Results:
824
-
825
- | Attribute | Description | Type | Values |
826
- | :------------ | :------------ | :------------ | :------------ |
827
- | **system** | System | string | android, ios, windows, macos, linux |
828
- | systemVs | System version | string | Windows: 2000, xp, 2003, vista, 7, 8, 8.1, 10 macOS: ... |
829
- | platform | Platform | string | desktop, mobile |
830
- | engine | Engine | string | webkit, gecko, presto, trident |
831
- | engineVs | Engine version | string | - |
832
- | supporter | Supporter | string | edge, opera, chrome, safari, firefox, iexplore |
833
- | supporterVs | Supporter version | string | - |
834
- | shell | Shell | string | (Optional) wechat, qq_browser, qq_app, uc, 360, 2345, sougou, liebao, maxthon, bilibili |
835
- | shellVs | Shell version | string | (Optional) 20/... |
836
- | appleType | Apple device type | string | (Optional) ipad, iphone, ipod, iwatch |
837
-
838
- Example: Determine the environment of the mobile QQ.
839
-
840
- ```javascript
841
- const { system, shell } = getBrowserInfo();
842
- const isMobileQQ = ['android', 'ios'].includes(system) && ['qq_browser', 'qq_app'].includes(shell);
843
- ```
844
-
845
- #### isSafePWAEnv
846
-
847
- Detect the margin of Safety. Determine if it is a secure PWA environment that it can run.
848
-
849
- Usage:
850
-
851
- ```javascript
852
- const ret = isSafePWAEnv();
853
- console.log(ret);
854
- ```
855
-
856
- Output:
857
-
858
- ```text
859
- true
860
- ```
861
-
862
- ### Web Performance
863
-
864
- #### getPerformance
865
-
866
- Get page load time(`PerformanceNavigationTiming`).
867
-
868
- This function uses the [`PerformanceNavigationTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming) API to get page load time data.
869
- The `PerformanceNavigationTiming` API provides more accurate and detailed information about page load time than the deprecated [`PerformanceTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming) API.
870
- If you are using an older browser that does not support `PerformanceNavigationTiming`, you can still use the `PerformanceTiming` API by using the previous version of this library ([`v3.9.7`](https://github.com/mazeyqian/mazey/releases/tag/v3.9.7)).
871
-
872
- Usage:
873
-
874
- ```javascript
875
- // `camelCase:false` (Default) Return underline(`a_b`) data.
876
- // `camelCase:true` Return hump(`aB`) data.
877
- getPerformance()
878
- .then(res => {
879
- console.log(JSON.stringify(res));
880
- })
881
- .catch(console.error);
882
- ```
883
-
884
- Output:
885
-
886
- ```text
887
- {"source":"PerformanceNavigationTiming","os":"others","os_version":"","device_type":"pc","network":"4g","screen_direction":"","unload_time":0,"redirect_time":0,"dns_time":0,"tcp_time":0,"ssl_time":0,"response_time":2,"download_time":2,"first_paint_time":288,"first_contentful_paint_time":288,"dom_ready_time":0,"onload_time":0,"white_time":0,"render_time":0,"decoded_body_size":718,"encoded_body_size":718}
888
- ```
889
-
890
- Results:
891
-
892
- | Attribute | Description | Type | Values |
893
- | :------------ | :------------ | :------------ | :------------ |
894
- | dns_time | DNS Lookup | number | domainLookupEnd - domainLookupStart |
895
- | tcp_time | Connection Negotiation | number | connectEnd - connectStart |
896
- | response_time | Requests and Responses | number | responseStart - requestStart |
897
- | white_time | White Screen | number | responseStart - navigationStart |
898
- | dom_ready_time | Dom Ready | number | domContentLoadedEventStart - navigationStart |
899
- | onload_time | Onload | number | loadEventStart - navigationStart |
900
- | render_time | EventEnd | number | loadEventEnd -navigationStart |
901
- | unload_time | Unload | number | (Optional) unloadEventEnd - unloadEventStart |
902
- | redirect_time | Redirect | number | (Optional) redirectEnd - redirectStart |
903
- | ssl_time | SSL | number | (Optional) connectEnd - secureConnectionStart |
904
- | download_time | Download | number | (Optional) responseEnd - responseStart |
905
-
906
- ### Debug
907
-
908
- #### genCustomConsole
909
-
910
- Custom console printing (`console`).
911
-
912
- Usage:
913
-
914
- ```javascript
915
- const myConsole = genCustomConsole('MazeyLog:');
916
- myConsole.log('I am string.');
917
- myConsole.info('I am boolean.', true);
918
- myConsole.info('I am number.', 123, 456);
919
- myConsole.info('I am object.', { a: 123, b: 456});
920
- ```
921
-
922
- Output:
923
-
924
- ```text
925
- MazeyLog: I am string.
926
- MazeyLog: I am boolean. true
927
- MazeyLog: I am number. 123 456
928
- MazeyLog: I am object. {a: 123, b: 456}
929
- ```
930
-
931
- ## Contributing
932
-
933
- ### Development Environment
934
-
935
- #### Node.js
936
-
937
- - v14.21.3
938
- - v14.7.0
939
-
940
- #### TypeScript
941
-
942
- - v4.4.4
943
-
944
- ### Scripts
945
-
946
- Install Dependencies:
947
-
948
- ```shell
949
- npm i
950
- ```
951
-
952
- Development:
953
-
954
- ```shell
955
- npm run dev
956
- ```
957
-
958
- Build:
959
-
960
- ```shell
961
- npm run build
962
- ```
963
-
964
- Document:
965
-
966
- ```shell
967
- npm run docs
968
- ```
969
-
970
- Test:
971
-
972
- ```shell
973
- npm run test
974
- ```
975
-
976
- ### Returns
977
-
978
- | Values | Description | Type |
979
- | :-------- | :--------------------------------------- | :------ |
980
- | ok | The operation was successful. | string |
981
- | loaded | Some assets have been loaded. | string |
982
- | fail | An error occurred. | string |
983
- | defined | The value is defined. | string |
984
- | undefined | The value is undefined. | string |
985
- | timeout | The operation timed out. | string |
986
- | true | The value is true. | boolean |
987
- | false | The value is false. | boolean |
988
-
989
- ## License
990
-
991
- This software is released under the terms of the [MIT license](https://github.com/mazeyqian/mazey/blob/main/LICENSE).
1
+ English | [简体中文](https://github.com/mazeyqian/mazey/blob/main/README_ZH.md)
2
+
3
+ # Mazey
4
+
5
+ [![npm version][npm-image]][npm-url]
6
+ [![l][l-image]][l-url]
7
+
8
+ [npm-image]: https://img.shields.io/npm/v/mazey
9
+ [npm-url]: https://npmjs.org/package/mazey
10
+ [l-image]: https://img.shields.io/npm/l/mazey
11
+ [l-url]: https://github.com/mazeyqian/mazey
12
+
13
+ Mazey is a functional library for daily front-end work. There are already many excellent libraries for front-end development, but creating a file named `utils.js` or `common.js` is generally used to supply common functions in projects. It's boring to copy similar functions across multiple projects. That's why I've created this library and will keep updating it to serve as a reliable resource for front-end needs.
14
+
15
+ ## Install
16
+
17
+ Use Mazey via [npm](https://www.npmjs.com/package/mazey).
18
+
19
+ ```shell
20
+ npm install mazey --save
21
+ ```
22
+
23
+ Use Mazey from CDN.
24
+
25
+ ```html
26
+ <script type="text/javascript" src="//i.mazey.net/mazey/lib/mazey.min.js"></script>
27
+ ```
28
+
29
+ Of course, you can also download this file and serve it yourself. The file locates at the `lib/mazey.min.js`.
30
+
31
+ ## Usage
32
+
33
+ Example: Use a function to verify if a value is a number suitable for standard calculations and comparisons.
34
+
35
+ Import from [npm](https://www.npmjs.com/package/mazey).
36
+
37
+ ```javascript
38
+ import { isNumber } from 'mazey';
39
+
40
+ const x = Infinity;
41
+ isNumber(x); // <=> typeof x === 'string' && !isNaN(x) && isFinite(x)
42
+ // Output: false
43
+ ```
44
+
45
+ Import from CDN.
46
+
47
+ ```html
48
+ <script type="text/javascript" src="//i.mazey.net/mazey/lib/mazey.min.js"></script>
49
+ <script>
50
+ const x = Infinity;
51
+ mazey.isNumber(x, { isInfinityAsNumber: true }); // <=> typeof x === 'string' && !isNaN(x)
52
+ // Output: true
53
+ </script>
54
+ ```
55
+
56
+ ## API Examples
57
+
58
+ There are some examples maintained by hand below. For more information, please check the [full documentation](https://mazey.cn/t/m).
59
+
60
+ ### Table of Contents
61
+
62
+ <!-- toc - begin -->
63
+ - Generated with ❤️
64
+ - [Load Resource](#load-resource)
65
+ - [loadScript](#loadscript)
66
+ - [loadScriptIfUndefined](#loadscriptifundefined)
67
+ - [loadCSS](#loadcss)
68
+ - [loadImage](#loadimage)
69
+ - [windowLoaded](#windowloaded)
70
+ - [Util](#util)
71
+ - [isNumber](#isnumber)
72
+ - [isJSONString](#isjsonstring)
73
+ - [isValidData](#isvaliddata)
74
+ - [genRndNumString](#genrndnumstring)
75
+ - [formatDate](#formatdate)
76
+ - [debounce](#debounce)
77
+ - [throttle](#throttle)
78
+ - [convertCamelToKebab](#convertcameltokebab)
79
+ - [convertCamelToUnder](#convertcameltounder)
80
+ - [deepCopy](#deepcopy)
81
+ - [URL](#url)
82
+ - [getQueryParam](#getqueryparam)
83
+ - [getUrlParam](#geturlparam)
84
+ - [getHashQueryParam](#gethashqueryparam)
85
+ - [getDomain](#getdomain)
86
+ - [updateQueryParam](#updatequeryparam)
87
+ - [isValidUrl](#isvalidurl)
88
+ - [isValidHttpUrl](#isvalidhttpurl)
89
+ - [Cache Data](#cache-data)
90
+ - [Cookie](#cookie)
91
+ - [Storage](#storage)
92
+ - [DOM](#dom)
93
+ - [addStyle](#addstyle)
94
+ - [Class](#class)
95
+ - [newLine](#newline)
96
+ - [Calculate and Formula](#calculate-and-formula)
97
+ - [inRate](#inrate)
98
+ - [longestComSubstring](#longestcomsubstring)
99
+ - [longestComSubsequence](#longestcomsubsequence)
100
+ - [Browser Information](#browser-information)
101
+ - [getBrowserInfo](#getbrowserinfo)
102
+ - [isSafePWAEnv](#issafepwaenv)
103
+ - [Web Performance](#web-performance)
104
+ - [getPerformance](#getperformance)
105
+ - [Debug](#debug)
106
+ - [genCustomConsole](#gencustomconsole)
107
+ <!-- toc - end -->
108
+
109
+ ### Load Resource
110
+
111
+ #### loadScript
112
+
113
+ Load a JavaScript file from the server and execute it.
114
+
115
+ Usage:
116
+
117
+ ```javascript
118
+ loadScript(
119
+ 'http://example.com/static/js/plugin-2.1.1.min.js',
120
+ {
121
+ id: 'iamid', // (Optional) script ID, default none
122
+ timeout: 5000, // (Optional) timeout, default `5000`
123
+ isDefer: false, // (Optional) defer, default `false`
124
+ }
125
+ )
126
+ .then(
127
+ res => {
128
+ console.log(`Load JavaScript script: ${res}`);
129
+ }
130
+ )
131
+ .catch(
132
+ err => {
133
+ console.error(`Load JavaScript script: ${err.message}`)
134
+ }
135
+ );
136
+ ```
137
+
138
+ Output:
139
+
140
+ ```text
141
+ Load JavaScript script: loaded
142
+ ```
143
+
144
+ #### loadScriptIfUndefined
145
+
146
+ Load a script from the given URL if it (`window['attribute']`) has not already been loaded.
147
+
148
+ Usage:
149
+
150
+ ```javascript
151
+ loadScriptIfUndefined('xyz', 'https://example.com/lib/xyz.min.js')
152
+ .then(() => {
153
+ console.log('xyz is loaded.');
154
+ })
155
+ .catch(err => {
156
+ console.log('Failed to load xyz.', err);
157
+ });
158
+ ```
159
+
160
+ Output:
161
+
162
+ ```text
163
+ xyz is loaded.
164
+ ```
165
+
166
+ #### loadCSS
167
+
168
+ Load a CSS file from the server.
169
+
170
+ Usage:
171
+
172
+ ```javascript
173
+ loadCSS(
174
+ 'http://example.com/path/example.css',
175
+ {
176
+ id: 'iamid', // Optional, link ID, default none
177
+ }
178
+ )
179
+ .then(
180
+ res => {
181
+ console.log(`Load CSS Success: ${res}`);
182
+ }
183
+ )
184
+ .catch(
185
+ err => {
186
+ console.error(`Load CSS Fail: ${err.message}`)
187
+ }
188
+ );
189
+ ```
190
+
191
+ Output:
192
+
193
+ ```text
194
+ Load CSS Success: loaded
195
+ ```
196
+
197
+ #### loadImage
198
+
199
+ Load an image from the given URL.
200
+
201
+ The target image will be loaded in the background, and the Promise status will change after the image is loaded. If the image fails to load, the Promise status will change to `reject` with the error object. If the image is loaded successfully, the Promise status will change to `resolve` with the image object. This method can be used to preload images and cache them in the browser. It can also be used to implement lazy loading of images.
202
+
203
+ Note that this method will not add the image to the DOM.
204
+
205
+ Usage:
206
+
207
+ ```javascript
208
+ loadImage('https://example.com/example.png')
209
+ .then((img) => {
210
+ console.log(img);
211
+ })
212
+ .catch((err) => {
213
+ console.log(err);
214
+ });
215
+ ```
216
+
217
+ #### windowLoaded
218
+
219
+ Check whether the page is loaded successfully (Keep the compatibility if the browser's `load` event has been triggered).
220
+
221
+ Usage:
222
+
223
+ ```javascript
224
+ windowLoaded(30) // second
225
+ .then(res => {
226
+ console.log(`Load Success: ${res}`);
227
+ })
228
+ .catch(err => {
229
+ console.log(`Load Timeout or Fail: ${err.message}`);
230
+ });
231
+ ```
232
+
233
+ Output:
234
+
235
+ ```text
236
+ Load Success: load
237
+ ```
238
+
239
+ ### Util
240
+
241
+ #### isNumber
242
+
243
+ Check whether it is a right number.
244
+
245
+ Usage:
246
+
247
+ ```javascript
248
+ const ret1 = isNumber(123);
249
+ const ret2 = isNumber('123');
250
+ // Default: NaN, Infinity is not Number
251
+ const ret3 = isNumber(Infinity);
252
+ const ret4 = isNumber(Infinity, { isInfinityAsNumber: true });
253
+ const ret5 = isNumber(NaN);
254
+ const ret6 = isNumber(NaN, { isNaNAsNumber: true, isInfinityAsNumber: true });
255
+ console.log(ret1, ret2, ret3, ret4, ret5, ret6);
256
+ ```
257
+
258
+ Output:
259
+
260
+ ```text
261
+ true false false true false true
262
+ ```
263
+
264
+ #### isJSONString
265
+
266
+ Check whether it is a valid JSON string.
267
+
268
+ Usage:
269
+
270
+ ```javascript
271
+ const ret1 = isJSONString(`['a', 'b', 'c']`);
272
+ const ret2 = isJSONString(`["a", "b", "c"]`);
273
+ console.log(ret1);
274
+ console.log(ret2);
275
+ ```
276
+
277
+ Output:
278
+
279
+ ```text
280
+ false
281
+ true
282
+ ```
283
+
284
+ #### isValidData
285
+
286
+ Determine the validity of the data.
287
+
288
+ Usage:
289
+
290
+ ```javascript
291
+ const validData = {
292
+ a: {
293
+ b: {
294
+ c: 413
295
+ }
296
+ }
297
+ };
298
+
299
+ const isValidDataResA = isValidData(validData, ['a', 'b', 'c'], 2333);
300
+ const isValidDataResB = isValidData(validData, ['a', 'b', 'c'], 413);
301
+ const isValidDataResC = isValidData(validData, ['d', 'd'], 413);
302
+
303
+ console.log('isValidDataResA:', isValidDataResA);
304
+ console.log('isValidDataResB:', isValidDataResB);
305
+ console.log('isValidDataResC:', isValidDataResC);
306
+ ```
307
+
308
+ Output:
309
+
310
+ ```text
311
+ isValidDataResA: false
312
+ isValidDataResB: true
313
+ isValidDataResC: false
314
+ ```
315
+
316
+ #### genRndNumString
317
+
318
+ Produce a random string of number, `genRndNumString(7)` => '7658495'.
319
+
320
+ Usage:
321
+
322
+ ```javascript
323
+ const ret1 = genRndNumString(4);
324
+ const ret2 = genRndNumString(7);
325
+ console.log(ret1);
326
+ console.log(ret2);
327
+ ```
328
+
329
+ Output:
330
+
331
+ ```text
332
+ 9730
333
+ 2262490
334
+ ```
335
+
336
+ #### formatDate
337
+
338
+ Return the formatted date string in the given format.
339
+
340
+ Usage:
341
+
342
+ ```javascript
343
+ const ret1 = formatDate();
344
+ const ret2 = formatDate('Tue Jan 11 2022 14:12:26 GMT+0800 (China Standard Time)', 'yyyy-MM-dd hh:mm:ss');
345
+ const ret3 = formatDate(1641881235000, 'yyyy-MM-dd hh:mm:ss');
346
+ const ret4 = formatDate(new Date(2014, 1, 11), 'MM/dd/yyyy');
347
+ console.log('Default formatDate value:', ret1);
348
+ console.log('String formatDate value:', ret2);
349
+ console.log('Number formatDate value:', ret3);
350
+ console.log('Date formatDate value:', ret4);
351
+ ```
352
+
353
+ Output:
354
+
355
+ ```text
356
+ Default formatDate value: 2023-01-11
357
+ String formatDate value: 2022-01-11 14:12:26
358
+ Number formatDate value: 2022-01-11 14:07:15
359
+ Date formatDate value: 02/11/2014
360
+ ```
361
+
362
+ #### debounce
363
+
364
+ Debounce
365
+
366
+ Usage:
367
+
368
+ ```javascript
369
+ const foo = debounce(() => {
370
+ console.log('The debounced function will only be invoked in 1000 milliseconds, the other invoking will disappear during the wait time.');
371
+ }, 1000, true);
372
+ ```
373
+
374
+ #### throttle
375
+
376
+ Throttle
377
+
378
+ Usage:
379
+
380
+ ```javascript
381
+ const foo = throttle(() => {
382
+ console.log('The function will be invoked at most once per every wait 1000 milliseconds.');
383
+ }, 1000, { leading: true });
384
+ ```
385
+
386
+ Reference: [Lodash](https://lodash.com/docs/4.17.15#throttle)
387
+
388
+ #### convertCamelToKebab
389
+
390
+ Transfer CamelCase to KebabCase.
391
+
392
+ Usage:
393
+
394
+ ```javascript
395
+ const ret1 = convertCamelToKebab('ABC');
396
+ const ret2 = convertCamelToKebab('aBC');
397
+ console.log(ret1);
398
+ console.log(ret2);
399
+ ```
400
+
401
+ Output:
402
+
403
+ ```text
404
+ a-b-c
405
+ a-b-c
406
+ ```
407
+
408
+ #### convertCamelToUnder
409
+
410
+ Transfer CamelCase to Underscore.
411
+
412
+ Usage:
413
+
414
+ ```javascript
415
+ const ret1 = convertCamelToUnder('ABC');
416
+ const ret2 = convertCamelToUnder('aBC');
417
+ console.log(ret1);
418
+ console.log(ret2);
419
+ ```
420
+
421
+ Output:
422
+
423
+ ```text
424
+ a_b_c
425
+ a_b_c
426
+ ```
427
+
428
+ #### deepCopy
429
+
430
+ Copy/Clone Object deeply.
431
+
432
+ Usage:
433
+
434
+ ```javascript
435
+ const ret1 = deepCopy(['a', 'b', 'c']);
436
+ const ret2 = deepCopy('abc');
437
+ console.log(ret1);
438
+ console.log(ret2);
439
+ ```
440
+
441
+ Output:
442
+
443
+ ```text
444
+ ['a', 'b', 'c']
445
+ abc
446
+ ```
447
+
448
+ ### URL
449
+
450
+ #### getQueryParam
451
+
452
+ Get the query param's value of the current Web URL(`location.search`).
453
+
454
+ Usage:
455
+
456
+ ```javascript
457
+ // http://example.com/?t1=1&t2=2&t3=3&t4=4#2333
458
+ // ?t1=1&t2=2&t3=3&t4=4
459
+ const p1 = getQueryParam('t3');
460
+ const p2 = getQueryParam('t4');
461
+ console.log(p1, p2);
462
+ ```
463
+
464
+ Output:
465
+
466
+ ```text
467
+ 3 4
468
+ ```
469
+
470
+ #### getUrlParam
471
+
472
+ Returns the value of the specified query parameter in the input URL.
473
+
474
+ Usage:
475
+
476
+ ```javascript
477
+ const p1 = getUrlParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't3');
478
+ const p2 = getUrlParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't4');
479
+ console.log(p1, p2);
480
+ ```
481
+
482
+ Output:
483
+
484
+ ```text
485
+ 3 4
486
+ ```
487
+
488
+ #### getHashQueryParam
489
+
490
+ Get the hash query param's value of the current Web URL(`location.hash`).
491
+
492
+ Usage:
493
+
494
+ ```javascript
495
+ // http://example.com/?#2333?t1=1&t2=2&t3=3&t4=4
496
+ // #2333?t1=1&t2=2&t3=3&t4=4
497
+ const p1 = getHashQueryParam('t3');
498
+ const p2 = getHashQueryParam('t4');
499
+ console.log(p1, p2);
500
+ ```
501
+
502
+ Output:
503
+
504
+ ```text
505
+ 3 4
506
+ ```
507
+
508
+ #### getDomain
509
+
510
+ Get the domain of URL, and other params.
511
+
512
+ Usage:
513
+
514
+ ```javascript
515
+ const ret1 = getDomain('http://example.com/?t1=1&t2=2&t3=3&t4=4');
516
+ const ret2 = getDomain('http://example.com/test/thanks?t1=1&t2=2&t3=3&t4=4', ['hostname', 'pathname']);
517
+ const ret3 = getDomain('http://example.com:7890/test/thanks', ['hostname']);
518
+ const ret4 = getDomain('http://example.com:7890/test/thanks', ['host']); // With Port
519
+ const ret5 = getDomain('http://example.com:7890/test/thanks', ['origin']);
520
+ const ret6 = getDomain('http://example.com:7890/test/thanks?id=1', ['origin', 'pathname', 'search']);
521
+ console.log(ret1);
522
+ console.log(ret2);
523
+ console.log(ret3);
524
+ console.log(ret4);
525
+ console.log(ret5);
526
+ console.log(ret6);
527
+ ```
528
+
529
+ Output:
530
+
531
+ ```text
532
+ example.com
533
+ example.com/test/thanks
534
+ example.com
535
+ example.com:7890
536
+ http://example.com:7890
537
+ http://example.com:7890/test/thanks?id=1
538
+ ```
539
+
540
+ #### updateQueryParam
541
+
542
+ Update the query param's value of the input URL.
543
+
544
+ Usage:
545
+
546
+ ```javascript
547
+ const ret1 = updateQueryParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't3', 'three');
548
+ const ret2 = updateQueryParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't4', 'four');
549
+ console.log(ret1);
550
+ console.log(ret2);
551
+ ```
552
+
553
+ Output:
554
+
555
+ ```text
556
+ http://example.com/?t1=1&t2=2&t3=three&t4=4
557
+ http://example.com/?t1=1&t2=2&t3=3&t4=four
558
+ ```
559
+
560
+ #### isValidUrl
561
+
562
+ Checks if the given string is a valid URL, including **scheme URLs**.
563
+
564
+ Usage:
565
+
566
+ ```javascript
567
+ const ret1 = isValidUrl('https://www.example.com');
568
+ const ret2 = isValidUrl('http://example.com/path/exx/ss');
569
+ const ret3 = isValidUrl('https://www.example.com/?q=hello&age=24#world');
570
+ const ret4 = isValidUrl('http://www.example.com/#world?id=9');
571
+ const ret5 = isValidUrl('ftp://example.com');
572
+ console.log(ret1, ret2, ret3, ret4, ret5);
573
+ ```
574
+
575
+ Output:
576
+
577
+ ```text
578
+ true true true true true
579
+ ```
580
+
581
+ If you are specifically checking for HTTP/HTTPS URLs, it is recommended to use the `isValidHttpUrl` function instead.
582
+ The `isValidUrl` function matches all scheme URLs, including FTP and other non-HTTP schemes.
583
+
584
+ #### isValidHttpUrl
585
+
586
+ Check if the given string is a valid HTTP/HTTPS URL.
587
+
588
+ Usage:
589
+
590
+ ```javascript
591
+ const ret1 = isValidHttpUrl('https://www.example.com');
592
+ const ret2 = isValidHttpUrl('http://example.com/path/exx/ss');
593
+ const ret3 = isValidHttpUrl('https://www.example.com/?q=hello&age=24#world');
594
+ const ret4 = isValidHttpUrl('http://www.example.com/#world?id=9');
595
+ const ret5 = isValidHttpUrl('ftp://example.com');
596
+ console.log(ret1, ret2, ret3, ret4, ret5);
597
+ ```
598
+
599
+ Output:
600
+
601
+ ```text
602
+ true true true true false
603
+ ```
604
+
605
+ ### Cache Data
606
+
607
+ #### Cookie
608
+
609
+ Handle Cookie.
610
+
611
+ Usage:
612
+
613
+ ```javascript
614
+ setCookie('test', '123', 30, 'example.com'); // key value day domain
615
+ const ret = getCookie('test');
616
+ console.log(ret);
617
+ ```
618
+
619
+ Output:
620
+
621
+ ```text
622
+ 123
623
+ ```
624
+
625
+ #### Storage
626
+
627
+ Handle Storage (Keep fit for JSON, it can transfer format automatically).
628
+
629
+ Usage:
630
+
631
+ ```javascript
632
+ setSessionStorage('test', '123');
633
+ const ret1 = getSessionStorage('test');
634
+ setLocalStorage('test', '123');
635
+ const ret2 = getLocalStorage('test');
636
+ console.log(ret1, ret2);
637
+
638
+ // or package in usage
639
+ const projectName = 'mazey';
640
+ function mSetLocalStorage (key, value) {
641
+ return setLocalStorage(`${projectName}_${key}`, value);
642
+ }
643
+
644
+ function mGetLocalStorage (key) {
645
+ return getLocalStorage(`${projectName}_${key}`);
646
+ }
647
+ ```
648
+
649
+ Output:
650
+
651
+ ```text
652
+ 123 123
653
+ ```
654
+
655
+ ### DOM
656
+
657
+ #### addStyle
658
+
659
+ Add `<style>` in `<head>`.
660
+
661
+ Example 1: Add the `<style>` with `id`, and repeated invoking will update the content instead of adding a new one.
662
+
663
+ ```javascript
664
+ addStyle(
665
+ `
666
+ body {
667
+ background-color: #333;
668
+ }
669
+ `,
670
+ {
671
+ id: 'test',
672
+ }
673
+ );
674
+ // <style id="test">
675
+ // body {
676
+ // background-color: #333;
677
+ // }
678
+ // </style>
679
+ ```
680
+
681
+ Example 2: Add the `<style>` without `id`, and repeated invoking will add a new one.
682
+
683
+ ```javascript
684
+ addStyle(
685
+ `
686
+ body {
687
+ background-color: #444;
688
+ }
689
+ `
690
+ );
691
+ // <style>
692
+ // body {
693
+ // background-color: #444;
694
+ // }
695
+ // </style>
696
+ ```
697
+
698
+ #### Class
699
+
700
+ Modify `class`.
701
+
702
+ Usage:
703
+
704
+ ```javascript
705
+ const dom = document.querySelector('#box');
706
+
707
+ // Determine `class`
708
+ hasClass(dom, 'test');
709
+ // Add `class`
710
+ addClass(dom, 'test');
711
+ // Remove `class`
712
+ removeClass(dom, 'test');
713
+ ```
714
+
715
+ #### newLine
716
+
717
+ Make a new line of HTML.
718
+
719
+ Usage:
720
+
721
+ ```javascript
722
+ const ret1 = newLine('a\nb\nc');
723
+ const ret2 = newLine('a\n\nbc');
724
+ console.log(ret1);
725
+ console.log(ret2);
726
+ ```
727
+
728
+ Output:
729
+
730
+ ```text
731
+ a<br />b<br />c
732
+ a<br /><br />bc
733
+ ```
734
+
735
+ ### Calculate and Formula
736
+
737
+ #### inRate
738
+
739
+ Hit probability (1% ~ 100%).
740
+
741
+ Usage:
742
+
743
+ ```javascript
744
+ const ret = inRate(0.5); // 0.01 ~ 1 true/false
745
+ console.log(ret);
746
+ ```
747
+
748
+ Output:
749
+
750
+ ```text
751
+ true
752
+ ```
753
+
754
+ Example: Test the precision.
755
+
756
+ ```javascript
757
+ // Test
758
+ let trueCount = 0;
759
+ let falseCount = 0;
760
+ new Array(1000000).fill(0).forEach(() => {
761
+ if (inRate(0.5)) {
762
+ trueCount++;
763
+ } else {
764
+ falseCount++;
765
+ }
766
+ });
767
+ console.log(trueCount, falseCount); // 499994 500006
768
+ ```
769
+
770
+ #### longestComSubstring
771
+
772
+ Computes the longest common substring of two strings.
773
+
774
+ Usage:
775
+
776
+ ```javascript
777
+ const ret = longestComSubstring('fish', 'finish');
778
+ console.log(ret);
779
+ ```
780
+
781
+ Output:
782
+
783
+ ```text
784
+ 3
785
+ ```
786
+
787
+ #### longestComSubsequence
788
+
789
+ Computes the longest common subsequence of two strings.
790
+
791
+ Usage:
792
+
793
+ ```javascript
794
+ const ret = longestComSubsequence('fish', 'finish');
795
+ console.log(ret);
796
+ ```
797
+
798
+ Output:
799
+
800
+ ```text
801
+ 4
802
+ ```
803
+
804
+ ### Browser Information
805
+
806
+ #### getBrowserInfo
807
+
808
+ Browser Information
809
+
810
+ Usage:
811
+
812
+ ```javascript
813
+ const ret = getBrowserInfo();
814
+ console.log(ret);
815
+ ```
816
+
817
+ Output:
818
+
819
+ ```text
820
+ {"engine":"webkit","engineVs":"537.36","platform":"desktop","supporter":"chrome","supporterVs":"85.0.4183.121","system":"windows","systemVs":"10"}
821
+ ```
822
+
823
+ Results:
824
+
825
+ | Attribute | Description | Type | Values |
826
+ | :------------ | :------------ | :------------ | :------------ |
827
+ | **system** | System | string | android, ios, windows, macos, linux |
828
+ | systemVs | System version | string | Windows: 2000, xp, 2003, vista, 7, 8, 8.1, 10 macOS: ... |
829
+ | platform | Platform | string | desktop, mobile |
830
+ | engine | Engine | string | webkit, gecko, presto, trident |
831
+ | engineVs | Engine version | string | - |
832
+ | supporter | Supporter | string | edge, opera, chrome, safari, firefox, iexplore |
833
+ | supporterVs | Supporter version | string | - |
834
+ | shell | Shell | string | (Optional) wechat, qq_browser, qq_app, uc, 360, 2345, sougou, liebao, maxthon, bilibili |
835
+ | shellVs | Shell version | string | (Optional) 20/... |
836
+ | appleType | Apple device type | string | (Optional) ipad, iphone, ipod, iwatch |
837
+
838
+ Example: Determine the environment of the mobile QQ.
839
+
840
+ ```javascript
841
+ const { system, shell } = getBrowserInfo();
842
+ const isMobileQQ = ['android', 'ios'].includes(system) && ['qq_browser', 'qq_app'].includes(shell);
843
+ ```
844
+
845
+ #### isSafePWAEnv
846
+
847
+ Detect the margin of Safety. Determine if it is a secure PWA environment that it can run.
848
+
849
+ Usage:
850
+
851
+ ```javascript
852
+ const ret = isSafePWAEnv();
853
+ console.log(ret);
854
+ ```
855
+
856
+ Output:
857
+
858
+ ```text
859
+ true
860
+ ```
861
+
862
+ ### Web Performance
863
+
864
+ #### getPerformance
865
+
866
+ Get page load time(`PerformanceNavigationTiming`).
867
+
868
+ This function uses the [`PerformanceNavigationTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming) API to get page load time data.
869
+ The `PerformanceNavigationTiming` API provides more accurate and detailed information about page load time than the deprecated [`PerformanceTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming) API.
870
+ If you are using an older browser that does not support `PerformanceNavigationTiming`, you can still use the `PerformanceTiming` API by using the previous version of this library ([`v3.9.7`](https://github.com/mazeyqian/mazey/releases/tag/v3.9.7)).
871
+
872
+ Usage:
873
+
874
+ ```javascript
875
+ // `camelCase:false` (Default) Return underline(`a_b`) data.
876
+ // `camelCase:true` Return hump(`aB`) data.
877
+ getPerformance()
878
+ .then(res => {
879
+ console.log(JSON.stringify(res));
880
+ })
881
+ .catch(console.error);
882
+ ```
883
+
884
+ Output:
885
+
886
+ ```text
887
+ {"source":"PerformanceNavigationTiming","os":"others","os_version":"","device_type":"pc","network":"4g","screen_direction":"","unload_time":0,"redirect_time":0,"dns_time":0,"tcp_time":0,"ssl_time":0,"response_time":2,"download_time":2,"first_paint_time":288,"first_contentful_paint_time":288,"dom_ready_time":0,"onload_time":0,"white_time":0,"render_time":0,"decoded_body_size":718,"encoded_body_size":718}
888
+ ```
889
+
890
+ Results:
891
+
892
+ | Attribute | Description | Type | Values |
893
+ | :------------ | :------------ | :------------ | :------------ |
894
+ | dns_time | DNS Lookup | number | domainLookupEnd - domainLookupStart |
895
+ | tcp_time | Connection Negotiation | number | connectEnd - connectStart |
896
+ | response_time | Requests and Responses | number | responseStart - requestStart |
897
+ | white_time | White Screen | number | responseStart - navigationStart |
898
+ | dom_ready_time | Dom Ready | number | domContentLoadedEventStart - navigationStart |
899
+ | onload_time | Onload | number | loadEventStart - navigationStart |
900
+ | render_time | EventEnd | number | loadEventEnd -navigationStart |
901
+ | unload_time | Unload | number | (Optional) unloadEventEnd - unloadEventStart |
902
+ | redirect_time | Redirect | number | (Optional) redirectEnd - redirectStart |
903
+ | ssl_time | SSL | number | (Optional) connectEnd - secureConnectionStart |
904
+ | download_time | Download | number | (Optional) responseEnd - responseStart |
905
+
906
+ ### Debug
907
+
908
+ #### genCustomConsole
909
+
910
+ Custom console printing (`console`).
911
+
912
+ Usage:
913
+
914
+ ```javascript
915
+ const myConsole = genCustomConsole('MazeyLog:');
916
+ myConsole.log('I am string.');
917
+ myConsole.info('I am boolean.', true);
918
+ myConsole.info('I am number.', 123, 456);
919
+ myConsole.info('I am object.', { a: 123, b: 456});
920
+ ```
921
+
922
+ Output:
923
+
924
+ ```text
925
+ MazeyLog: I am string.
926
+ MazeyLog: I am boolean. true
927
+ MazeyLog: I am number. 123 456
928
+ MazeyLog: I am object. {a: 123, b: 456}
929
+ ```
930
+
931
+ ## Contributing
932
+
933
+ ### Development Environment
934
+
935
+ #### Node.js
936
+
937
+ - v14.21.3
938
+ - v14.7.0
939
+
940
+ #### TypeScript
941
+
942
+ - v4.4.4
943
+
944
+ ### Scripts
945
+
946
+ Install Dependencies:
947
+
948
+ ```shell
949
+ npm i
950
+ ```
951
+
952
+ Development:
953
+
954
+ ```shell
955
+ npm run dev
956
+ ```
957
+
958
+ Build:
959
+
960
+ ```shell
961
+ npm run build
962
+ ```
963
+
964
+ Document:
965
+
966
+ ```shell
967
+ npm run docs
968
+ ```
969
+
970
+ Test:
971
+
972
+ ```shell
973
+ npm run test
974
+ ```
975
+
976
+ ### Returns
977
+
978
+ | Values | Description | Type |
979
+ | :-------- | :--------------------------------------- | :------ |
980
+ | ok | The operation was successful. | string |
981
+ | loaded | Some assets have been loaded. | string |
982
+ | fail | An error occurred. | string |
983
+ | defined | The value is defined. | string |
984
+ | undefined | The value is undefined. | string |
985
+ | timeout | The operation timed out. | string |
986
+ | true | The value is true. | boolean |
987
+ | false | The value is false. | boolean |
988
+
989
+ ## License
990
+
991
+ This software is released under the terms of the [MIT license](https://github.com/mazeyqian/mazey/blob/main/LICENSE).