mazey 4.0.7 → 4.1.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,990 +1,990 @@
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
- const y = Infinity;
42
- // <=> typeof x === 'number' && !isNaN(x) && isFinite(x)
43
- isNumber(x); // Output: true
44
- isNumber(y); // Output: false
45
- ```
46
-
47
- Import from CDN.
48
-
49
- ```html
50
- <script type="text/javascript" src="//i.mazey.net/mazey/lib/mazey.min.js"></script>
51
- <script>
52
- const x = Infinity;
53
- // <=> typeof x === 'string' && !isNaN(x)
54
- mazey.isNumber(x, { isInfinityAsNumber: true }); // Output: true
55
- </script>
56
- ```
57
-
58
- ## API Examples
59
-
60
- There are some examples maintained by hand below. For more information, please check the [full documentation](https://mazey.cn/t/m).
61
-
62
- ### Table of Contents
63
-
64
- <!-- toc - begin -->
65
- - Generated with ❤️
66
- - [Load Resource](#load-resource)
67
- - [loadScript](#loadscript)
68
- - [loadScriptIfUndefined](#loadscriptifundefined)
69
- - [loadCSS](#loadcss)
70
- - [loadImage](#loadimage)
71
- - [windowLoaded](#windowloaded)
72
- - [Util](#util)
73
- - [isNumber](#isnumber)
74
- - [isJSONString](#isjsonstring)
75
- - [isValidData](#isvaliddata)
76
- - [genRndNumString](#genrndnumstring)
77
- - [formatDate](#formatdate)
78
- - [debounce](#debounce)
79
- - [throttle](#throttle)
80
- - [convertCamelToKebab](#convertcameltokebab)
81
- - [convertCamelToUnder](#convertcameltounder)
82
- - [deepCopy](#deepcopy)
83
- - [URL](#url)
84
- - [getQueryParam](#getqueryparam)
85
- - [getUrlParam](#geturlparam)
86
- - [getHashQueryParam](#gethashqueryparam)
87
- - [getDomain](#getdomain)
88
- - [updateQueryParam](#updatequeryparam)
89
- - [isValidUrl](#isvalidurl)
90
- - [isValidHttpUrl](#isvalidhttpurl)
91
- - [Cache Data](#cache-data)
92
- - [Cookie](#cookie)
93
- - [Storage](#storage)
94
- - [DOM](#dom)
95
- - [addStyle](#addstyle)
96
- - [Class](#class)
97
- - [newLine](#newline)
98
- - [Calculate and Formula](#calculate-and-formula)
99
- - [inRate](#inrate)
100
- - [longestComSubstring](#longestcomsubstring)
101
- - [longestComSubsequence](#longestcomsubsequence)
102
- - [Browser Information](#browser-information)
103
- - [getBrowserInfo](#getbrowserinfo)
104
- - [isSafePWAEnv](#issafepwaenv)
105
- - [Web Performance](#web-performance)
106
- - [getPerformance](#getperformance)
107
- - [Debug](#debug)
108
- - [genCustomConsole](#gencustomconsole)
109
- <!-- toc - end -->
110
-
111
- ### Load Resource
112
-
113
- #### loadScript
114
-
115
- Load a JavaScript file from the server and execute it.
116
-
117
- Usage:
118
-
119
- ```javascript
120
- loadScript(
121
- 'http://example.com/static/js/plugin-2.1.1.min.js',
122
- {
123
- id: 'iamid', // (Optional) script ID, default none
124
- timeout: 5000, // (Optional) timeout, default `5000`
125
- isDefer: false, // (Optional) defer, default `false`
126
- }
127
- )
128
- .then(
129
- res => {
130
- console.log(`Load JavaScript script: ${res}`);
131
- }
132
- )
133
- .catch(
134
- err => {
135
- console.error(`Load JavaScript script: ${err.message}`)
136
- }
137
- );
138
- ```
139
-
140
- Output:
141
-
142
- ```text
143
- Load JavaScript script: loaded
144
- ```
145
-
146
- #### loadScriptIfUndefined
147
-
148
- Load a script from the given URL if it (`window['attribute']`) has not already been loaded.
149
-
150
- Usage:
151
-
152
- ```javascript
153
- loadScriptIfUndefined('xyz', 'https://example.com/lib/xyz.min.js')
154
- .then(() => {
155
- console.log('xyz is loaded.');
156
- })
157
- .catch(err => {
158
- console.log('Failed to load xyz.', err);
159
- });
160
- ```
161
-
162
- Output:
163
-
164
- ```text
165
- xyz is loaded.
166
- ```
167
-
168
- #### loadCSS
169
-
170
- Load a CSS file from the server.
171
-
172
- Usage:
173
-
174
- ```javascript
175
- loadCSS(
176
- 'http://example.com/path/example.css',
177
- {
178
- id: 'iamid', // Optional, link ID, default none
179
- }
180
- )
181
- .then(
182
- res => {
183
- console.log(`Load CSS Success: ${res}`);
184
- }
185
- )
186
- .catch(
187
- err => {
188
- console.error(`Load CSS Fail: ${err.message}`)
189
- }
190
- );
191
- ```
192
-
193
- Output:
194
-
195
- ```text
196
- Load CSS Success: loaded
197
- ```
198
-
199
- #### loadImage
200
-
201
- Load an image from the given URL.
202
-
203
- 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.
204
-
205
- Note that this method will not add the image to the DOM.
206
-
207
- Usage:
208
-
209
- ```javascript
210
- loadImage('https://example.com/example.png')
211
- .then((img) => {
212
- console.log(img);
213
- })
214
- .catch((err) => {
215
- console.log(err);
216
- });
217
- ```
218
-
219
- #### windowLoaded
220
-
221
- Check whether the page is loaded successfully (Keep the compatibility if the browser's `load` event has been triggered).
222
-
223
- Usage:
224
-
225
- ```javascript
226
- windowLoaded(30) // second
227
- .then(res => {
228
- console.log(`Load Success: ${res}`);
229
- })
230
- .catch(err => {
231
- console.log(`Load Timeout or Fail: ${err.message}`);
232
- });
233
- ```
234
-
235
- Output:
236
-
237
- ```text
238
- Load Success: load
239
- ```
240
-
241
- ### Util
242
-
243
- #### isNumber
244
-
245
- Check whether it is a right number.
246
-
247
- Usage:
248
-
249
- ```javascript
250
- const ret1 = isNumber(123);
251
- const ret2 = isNumber('123');
252
- // Default: NaN, Infinity is not Number
253
- const ret3 = isNumber(Infinity);
254
- const ret4 = isNumber(Infinity, { isInfinityAsNumber: true });
255
- const ret5 = isNumber(NaN);
256
- const ret6 = isNumber(NaN, { isNaNAsNumber: true, isInfinityAsNumber: true });
257
- console.log(ret1, ret2, ret3, ret4, ret5, ret6);
258
- ```
259
-
260
- Output:
261
-
262
- ```text
263
- true false false true false true
264
- ```
265
-
266
- #### isJSONString
267
-
268
- Check whether it is a valid JSON string.
269
-
270
- Usage:
271
-
272
- ```javascript
273
- const ret1 = isJSONString(`['a', 'b', 'c']`);
274
- const ret2 = isJSONString(`["a", "b", "c"]`);
275
- console.log(ret1);
276
- console.log(ret2);
277
- ```
278
-
279
- Output:
280
-
281
- ```text
282
- false
283
- true
284
- ```
285
-
286
- #### isValidData
287
-
288
- Determine the validity of the data.
289
-
290
- Usage:
291
-
292
- ```javascript
293
- const validData = {
294
- a: {
295
- b: {
296
- c: 413
297
- }
298
- }
299
- };
300
- const isValidDataResA = isValidData(validData, ['a', 'b', 'c'], 2333);
301
- const isValidDataResB = isValidData(validData, ['a', 'b', 'c'], 413);
302
- const isValidDataResC = isValidData(validData, ['d', 'd'], 413);
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
- - v16.19.0
938
-
939
- #### TypeScript
940
-
941
- - v5.1.6
942
-
943
- ### Scripts
944
-
945
- Install Dependencies:
946
-
947
- ```bash
948
- npm i
949
- ```
950
-
951
- Development:
952
-
953
- ```bash
954
- npm run dev
955
- ```
956
-
957
- Build:
958
-
959
- ```bash
960
- npm run build
961
- ```
962
-
963
- Document:
964
-
965
- ```bash
966
- npm run docs
967
- ```
968
-
969
- Test:
970
-
971
- ```bash
972
- npm run test
973
- ```
974
-
975
- ### Returns
976
-
977
- | Values | Description | Type |
978
- | :-------- | :--------------------------------------- | :------ |
979
- | ok | The operation was successful. | string |
980
- | loaded | Some assets have been loaded. | string |
981
- | fail | An error occurred. | string |
982
- | defined | The value is defined. | string |
983
- | undefined | The value is undefined. | string |
984
- | timeout | The operation timed out. | string |
985
- | true | The value is true. | boolean |
986
- | false | The value is false. | boolean |
987
-
988
- ## License
989
-
990
- 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
+ const y = Infinity;
42
+ // <=> typeof x === 'number' && !isNaN(x) && isFinite(x)
43
+ isNumber(x); // Output: true
44
+ isNumber(y); // Output: false
45
+ ```
46
+
47
+ Import from CDN.
48
+
49
+ ```html
50
+ <script type="text/javascript" src="//i.mazey.net/mazey/lib/mazey.min.js"></script>
51
+ <script>
52
+ const x = Infinity;
53
+ // <=> typeof x === 'string' && !isNaN(x)
54
+ mazey.isNumber(x, { isInfinityAsNumber: true }); // Output: true
55
+ </script>
56
+ ```
57
+
58
+ ## API Examples
59
+
60
+ There are some examples maintained by hand below. For more information, please check the [full documentation](https://mazey.cn/t/m).
61
+
62
+ ### Table of Contents
63
+
64
+ <!-- toc - begin -->
65
+ - Generated with ❤️
66
+ - [Load Resource](#load-resource)
67
+ - [loadScript](#loadscript)
68
+ - [loadScriptIfUndefined](#loadscriptifundefined)
69
+ - [loadCSS](#loadcss)
70
+ - [loadImage](#loadimage)
71
+ - [windowLoaded](#windowloaded)
72
+ - [Util](#util)
73
+ - [isNumber](#isnumber)
74
+ - [isJSONString](#isjsonstring)
75
+ - [isValidData](#isvaliddata)
76
+ - [genRndNumString](#genrndnumstring)
77
+ - [formatDate](#formatdate)
78
+ - [debounce](#debounce)
79
+ - [throttle](#throttle)
80
+ - [convertCamelToKebab](#convertcameltokebab)
81
+ - [convertCamelToUnder](#convertcameltounder)
82
+ - [deepCopy](#deepcopy)
83
+ - [URL](#url)
84
+ - [getQueryParam](#getqueryparam)
85
+ - [getUrlParam](#geturlparam)
86
+ - [getHashQueryParam](#gethashqueryparam)
87
+ - [getDomain](#getdomain)
88
+ - [updateQueryParam](#updatequeryparam)
89
+ - [isValidUrl](#isvalidurl)
90
+ - [isValidHttpUrl](#isvalidhttpurl)
91
+ - [Store](#cache-data)
92
+ - [Cookie](#cookie)
93
+ - [Storage](#storage)
94
+ - [DOM](#dom)
95
+ - [addStyle](#addstyle)
96
+ - [Class](#class)
97
+ - [newLine](#newline)
98
+ - [Calculate and Formula](#calculate-and-formula)
99
+ - [inRate](#inrate)
100
+ - [longestComSubstring](#longestcomsubstring)
101
+ - [longestComSubsequence](#longestcomsubsequence)
102
+ - [Browser Information](#browser-information)
103
+ - [getBrowserInfo](#getbrowserinfo)
104
+ - [isSafePWAEnv](#issafepwaenv)
105
+ - [Web Performance](#web-performance)
106
+ - [getPerformance](#getperformance)
107
+ - [Debug](#debug)
108
+ - [genCustomConsole](#gencustomconsole)
109
+ <!-- toc - end -->
110
+
111
+ ### Load Resource
112
+
113
+ #### loadScript
114
+
115
+ Load a JavaScript file from the server and execute it.
116
+
117
+ Usage:
118
+
119
+ ```javascript
120
+ loadScript(
121
+ 'http://example.com/static/js/plugin-2.1.1.min.js',
122
+ {
123
+ id: 'iamid', // (Optional) script ID, default none
124
+ timeout: 5000, // (Optional) timeout, default `5000`
125
+ isDefer: false, // (Optional) defer, default `false`
126
+ }
127
+ )
128
+ .then(
129
+ res => {
130
+ console.log(`Load JavaScript script: ${res}`);
131
+ }
132
+ )
133
+ .catch(
134
+ err => {
135
+ console.error(`Load JavaScript script: ${err.message}`)
136
+ }
137
+ );
138
+ ```
139
+
140
+ Output:
141
+
142
+ ```text
143
+ Load JavaScript script: loaded
144
+ ```
145
+
146
+ #### loadScriptIfUndefined
147
+
148
+ Load a script from the given URL if it (`window['attribute']`) has not already been loaded.
149
+
150
+ Usage:
151
+
152
+ ```javascript
153
+ loadScriptIfUndefined('xyz', 'https://example.com/lib/xyz.min.js')
154
+ .then(() => {
155
+ console.log('xyz is loaded.');
156
+ })
157
+ .catch(err => {
158
+ console.log('Failed to load xyz.', err);
159
+ });
160
+ ```
161
+
162
+ Output:
163
+
164
+ ```text
165
+ xyz is loaded.
166
+ ```
167
+
168
+ #### loadCSS
169
+
170
+ Load a CSS file from the server.
171
+
172
+ Usage:
173
+
174
+ ```javascript
175
+ loadCSS(
176
+ 'http://example.com/path/example.css',
177
+ {
178
+ id: 'iamid', // Optional, link ID, default none
179
+ }
180
+ )
181
+ .then(
182
+ res => {
183
+ console.log(`Load CSS Success: ${res}`);
184
+ }
185
+ )
186
+ .catch(
187
+ err => {
188
+ console.error(`Load CSS Fail: ${err.message}`)
189
+ }
190
+ );
191
+ ```
192
+
193
+ Output:
194
+
195
+ ```text
196
+ Load CSS Success: loaded
197
+ ```
198
+
199
+ #### loadImage
200
+
201
+ Load an image from the given URL.
202
+
203
+ 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.
204
+
205
+ Note that this method will not add the image to the DOM.
206
+
207
+ Usage:
208
+
209
+ ```javascript
210
+ loadImage('https://example.com/example.png')
211
+ .then((img) => {
212
+ console.log(img);
213
+ })
214
+ .catch((err) => {
215
+ console.log(err);
216
+ });
217
+ ```
218
+
219
+ #### windowLoaded
220
+
221
+ Check whether the page is loaded successfully (Keep the compatibility if the browser's `load` event has been triggered).
222
+
223
+ Usage:
224
+
225
+ ```javascript
226
+ windowLoaded()
227
+ .then(res => {
228
+ console.log(`Load Success: ${res}`);
229
+ })
230
+ .catch(err => {
231
+ console.log(`Load Timeout or Fail: ${err.message}`);
232
+ });
233
+ ```
234
+
235
+ Output:
236
+
237
+ ```text
238
+ Load Success: load
239
+ ```
240
+
241
+ ### Util
242
+
243
+ #### isNumber
244
+
245
+ Check whether it is a right number.
246
+
247
+ Usage:
248
+
249
+ ```javascript
250
+ const ret1 = isNumber(123);
251
+ const ret2 = isNumber('123');
252
+ // Default: NaN, Infinity is not Number
253
+ const ret3 = isNumber(Infinity);
254
+ const ret4 = isNumber(Infinity, { isInfinityAsNumber: true });
255
+ const ret5 = isNumber(NaN);
256
+ const ret6 = isNumber(NaN, { isNaNAsNumber: true, isInfinityAsNumber: true });
257
+ console.log(ret1, ret2, ret3, ret4, ret5, ret6);
258
+ ```
259
+
260
+ Output:
261
+
262
+ ```text
263
+ true false false true false true
264
+ ```
265
+
266
+ #### isJSONString
267
+
268
+ Check whether it is a valid JSON string.
269
+
270
+ Usage:
271
+
272
+ ```javascript
273
+ const ret1 = isJSONString(`['a', 'b', 'c']`);
274
+ const ret2 = isJSONString(`["a", "b", "c"]`);
275
+ console.log(ret1);
276
+ console.log(ret2);
277
+ ```
278
+
279
+ Output:
280
+
281
+ ```text
282
+ false
283
+ true
284
+ ```
285
+
286
+ #### isValidData
287
+
288
+ Determine the validity of the data.
289
+
290
+ Usage:
291
+
292
+ ```javascript
293
+ const validData = {
294
+ a: {
295
+ b: {
296
+ c: 413
297
+ }
298
+ }
299
+ };
300
+ const isValidDataResA = isValidData(validData, ['a', 'b', 'c'], 2333);
301
+ const isValidDataResB = isValidData(validData, ['a', 'b', 'c'], 413);
302
+ const isValidDataResC = isValidData(validData, ['d', 'd'], 413);
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
+ ### Store
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
+ - v16.19.0
938
+
939
+ #### TypeScript
940
+
941
+ - v5.1.6
942
+
943
+ ### Scripts
944
+
945
+ Install Dependencies:
946
+
947
+ ```bash
948
+ npm i
949
+ ```
950
+
951
+ Development:
952
+
953
+ ```bash
954
+ npm run dev
955
+ ```
956
+
957
+ Build:
958
+
959
+ ```bash
960
+ npm run build
961
+ ```
962
+
963
+ Document:
964
+
965
+ ```bash
966
+ npm run docs
967
+ ```
968
+
969
+ Test:
970
+
971
+ ```bash
972
+ npm run test
973
+ ```
974
+
975
+ ### Returns
976
+
977
+ | Values | Description | Type |
978
+ | :-------- | :--------------------------------------- | :------ |
979
+ | ok | The operation was successful. | string |
980
+ | loaded | Some assets have been loaded. | string |
981
+ | fail | An error occurred. | string |
982
+ | defined | The value is defined. | string |
983
+ | undefined | The value is undefined. | string |
984
+ | timeout | The operation timed out. | string |
985
+ | true | The value is true. | boolean |
986
+ | false | The value is false. | boolean |
987
+
988
+ ## License
989
+
990
+ This software is released under the terms of the [MIT license](https://github.com/mazeyqian/mazey/blob/main/LICENSE).