mazey 3.11.6 → 3.12.0

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