utils-lib-js 2.0.6 → 2.0.7

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.en.md CHANGED
@@ -1,540 +1,705 @@
1
1
  # utils-lib-js
2
2
 
3
- #### Introduction
4
- JavaScript utility functions, packaging some commonly used js functions
5
-
6
- #### Software Architecture
7
- Software architecture specification
8
-
9
-
10
- #### installation tutorial
3
+ ## Introduction
11
4
 
12
- 1. pnpm i
13
- 2. pnpm build
5
+ JavaScript utility functions, packaging some commonly used js functions
14
6
 
15
- #### Usage instructions
7
+ ## Debugging instructions
16
8
 
17
9
  1. pnpm build
18
10
  2. pnpm debug (debug source)
11
+ 3. Import the tool library in esm, cjs, and window environments
19
12
 
20
- #### Contribute
13
+ ## Contribute
21
14
 
22
15
  1. Fork the local warehouse
23
- 2. Create a branch of Feat_xxx
16
+ 2. Star Warehouse
24
17
  3. Submit the code
25
18
  4. Create a Pull Request
26
19
 
27
- #### function
28
- Interface:
20
+ ## Instructions for use
29
21
 
30
- export type IKey = string | symbol | number
22
+ ### Install
31
23
 
32
- ##### Object type
24
+ `npm install utils-lib-js`
25
+ or
26
+ `yarn add utils-lib-js`
27
+ or
28
+ `pnpm install utils-lib-js`
33
29
 
34
- export interface IObject<T> {
35
- [key: IKey]: T | IObject<any>
36
- }
30
+ ### Introduce
37
31
 
38
- export interface IPromise extends IObject<any> {
39
- promise: Promise<void>
40
- resolve: (res: any) => unknown
41
- reject: (err: any) => unknown
42
- }
32
+ #### ESM
33
+
34
+ ```javascript
35
+ import { defer, messageCenter, TaskQueue, Request } from "utils-lib-js";
36
+ ```
37
+
38
+ #### CJS
39
+
40
+ ```javascript
41
+ const { defer, messageCenter, TaskQueue } = require("utils-lib-js");
42
+ ```
43
+
44
+ #### in your browser
45
+
46
+ ```html
47
+ <script src="./node_modules/utils-lib-js/dist/umd/index.js"></script>
48
+ <script>
49
+ console.log(UtilsLib);
50
+ </script>
51
+ ```
52
+
53
+ ### TS interface comment
54
+
55
+ With reference to https://gitee.com/DieHunter/utils-lib-js/blob/master/src/types.ts
56
+
57
+ ### Code demo
43
58
 
44
- export type IInstance<T> = {
45
- _instance: Function
46
- } & T
59
+ #### base module
47
60
 
48
- export type IDemoteArray<T> = Array<IDemoteArray<T> | T>
61
+ ##### 1. `randomNum(min: number, max: number, bool? : boolean): number`
49
62
 
50
- ##### base
63
+ Generates random integers within the specified range.
51
64
 
52
- /** Generates interval random numbers
53
- * @param {number} min Minimum interval
54
- * @param {number} max Maximum range
55
- * @param {boolean} bool Contains the maximum value
56
- * @return {number} A random number
57
- * * /
65
+ - 'min' : indicates the minimum value (including).
66
+ - 'max' : indicates the maximum value (inclusive).
67
+ - 'bool' : Indicates whether the maximum value is contained. The default value is false.
58
68
 
59
- export type IRandomNum = (min: number, max: number, bool? : boolean) => number
69
+ ```javascript
70
+ const randomNumber = randomNum(1, 10);
71
+ console.log(randomNumber); // Generates a random integer between 1 and 10
72
+ ```
60
73
 
61
- /** Gets the parameters of the url
62
- * @param {string} url Indicates the address to be intercepted
63
- * @return {object} Parameter object
64
- * * /
74
+ ##### 2. `urlSplit(url: string): object`
65
75
 
66
- export type IUrlSplit = (url: string) => IObject<any>
76
+ Parses URL query parameters into objects.
67
77
 
68
- /** Adds parameters for the url
69
- * @param {string} url Address to which the parameter is to be added
70
- * @param {object} query Specifies the parameter to be added
71
- * @return {string} The url after the parameter is added
72
- * * /
78
+ - 'url' : indicates the URL containing the query parameter.
73
79
 
74
- export type IUrlJoin = (url: string, query: object) => string
80
+ ```javascript
81
+ const url = "https://example.com/path?param1=value1&param2=value2";
82
+ const params = urlSplit(url);
83
+ console.log(params);
84
+ // Output: {param1: 'value1', param2: 'value2'}
85
+ ```
75
86
 
76
- /** Gets the data type
77
- * @param {any} data Indicates the data to be detected
78
- * @return {string} Data type
79
- * * /
87
+ ##### 3. `urlJoin(url: string, query: object): string`
80
88
 
81
- export type IGetType<T> = (data: any) => typeof data | T[keyof T] | "null";
89
+ Converts the object to a URL query parameter and concatenates it with the original URL.
82
90
 
83
- /** Determine the data type in batches
84
- * @param {any} data Indicates the data to be detected
85
- * @param {any} whiteList Indicates a list of data types
86
- * @return {boolean} Whether it is in the whitelist
87
- * * /
91
+ - 'url' : indicates the original URL.
92
+ - 'query' : object containing query parameters.
88
93
 
89
- export type IGetTypeByList = (data: any, whiteList: string[]) => boolean;
94
+ ```javascript
95
+ const url = "https://example.com/path";
96
+ const query = { param1: "value1", param2: "value2" };
97
+ const newUrl = urlJoin(url, query);
98
+ console.log(newUrl);
99
+ // Output: https://example.com/path?param1=value1&param2=value2
100
+ ```
90
101
 
102
+ ##### 4. `getType(data: any): string`
91
103
 
92
- ##### object
104
+ Get the type of data.
93
105
 
94
- /**lodash _.get() to get a certain level attribute of the object
95
- * @param {IObject} object Indicates the target object
96
- * @param {string} key object hierarchy
97
- * @param {any} defaultValue Default value if not obtained
98
- * @return {IObject[IKey]} A property of an object
99
- * * /
106
+ - 'data' : indicates the data to be checked.
100
107
 
101
- export type IGetValue = <T, U = IObject<T> | IObject<T>[IKey]>(object: U, key: string, defaultValue? : any) => U
108
+ ```javascript
109
+ const dataType = getType("Hello, World!");
110
+ console.log(dataType); // Output: string
111
+ ```
102
112
 
103
- /**lodash _.set(), which assigns a level attribute to the object
104
- * @param {IObject} object Indicates the target object
105
- * @param {string} key object hierarchy
106
- * @param {any} value Specifies the value to be assigned
107
- * @return {IObject} Target object
108
- * * /
113
+ ##### 5. `getTypeByList(data: any, whiteList: string[]): boolean`
109
114
 
110
- export type ISetValue = <T>(object: IObject<T>, key: string, value? : any) => IObject<T>
115
+ Check whether the data type is in the whitelist.
111
116
 
112
- /** Object mixed in
113
- * @param {IObject} target Indicates the target object
114
- * @param {string} source Set of objects to be mixed in
115
- * @param {boolean} overwrite Whether to overwrite the original attribute
116
- * @return {IObject} Target object
117
- * * /
117
+ - 'data' : indicates the data to be checked.
118
+ - 'whiteList' : indicates the list of allowed data types.
118
119
 
119
- export type IMixIn = <U extends IObject<any>>(target? : U, source? : IObject<any>, overwrite? : boolean) => U
120
+ ```javascript
121
+ const data = 42;
122
+ const allowedTypes = ["number", "string"];
123
+ const isTypeAllowed = getTypeByList(data, allowedTypes);
124
+ console.log(isTypeAllowed); // Output: true
125
+ ```
120
126
 
121
- /** Enumeration value reverse mapping
122
- * @param {IObject<string>} target Indicates the target object
123
- * @return {IObject<string>} Target object
124
- * * /
127
+ #### object module
125
128
 
126
- export type IEnumInversion = (target: IObject<string>) => IObject<string>
129
+ ##### 1. `getValue(object: object, key: string, defaultValue: any = ''): any`
127
130
 
128
- /** Object replication
129
- * @param {IObject<any>} target Indicates the target object
130
- * @return {IObject} Target object
131
- * * /
131
+ Gets the value of the specified path in the object.
132
132
 
133
- export type ICloneDeep = (target? : any) => any
133
+ - 'object' : indicates the target object.
134
+ - 'key' : the path to the value to be obtained.
135
+ - 'defaultValue' : Default value, returned if the path does not exist.
134
136
 
135
- /** Generates the initial value of the object type
136
- * @param {string} type Indicates the data type
137
- * @param {any} __init Initial value
138
- * @return {any} Target object
139
- * * /
137
+ ```javascript
138
+ const obj = { a: { b: { c: 42 } } };
139
+ const value = getValue(obj, "a.b.c", "default");
140
+ console.log(value); // Output: 42
141
+ ```
140
142
 
141
- export type ICreateObjectVariable = (type: string, source? : any) => any
143
+ ##### 2. `setValue(object: object, key: string, value: any = {}): object`
142
144
 
143
- /** object. create generates a new Object based on the source object
144
- * @param {Function|Object} source Source object
145
- * @return {Function|Object} Object product
146
- * * /
145
+ Sets the value of the specified path in the object.
147
146
 
148
- export type ICreateObject = <T, U extends T>(source: T) => U
147
+ - 'object' : indicates the target object.
148
+ - 'key' : path to the value to be set.
149
+ - 'value' : indicates the value to be set.
149
150
 
150
- Inheritance of the /** class
151
- * @param {Function} source Source object
152
- * @return {Function} inheritance product
153
- * * /
151
+ ```javascript
152
+ const obj = { a: { b: { c: 42 } } };
153
+ setValue(obj, "a.b.d", "new value");
154
+ console.log(obj); // Output: {a: {b: {c: 42, d: 'new value'}}}
155
+ ```
154
156
 
155
- export type IInherit = <T extends Function>(source: T, target? : Function) => Function
157
+ ##### 3. `mixIn(target: object, source: object = {}, overwrite: boolean = false): object`
156
158
 
157
- /** Generates an instance singleton of the class
158
- * @param {Function} classProto class
159
- * @param {Boolean} overwrite Whether to overwrite an existing singleton
160
- * @param {any[]} Parameter of the params constructor
161
- * @return {IObject} instantiated singleton
162
- * * /
159
+ Mixes the properties of the source object into the target object.
163
160
 
164
- export type IGetInstance = (classProto: IInstance<FunctionConstructor>, overwrite? : boolean, ... params: any[]) => Function
161
+ - 'target' : indicates the target object.
162
+ - 'source' : indicates the source object.
163
+ - 'overwrite' : Whether to overwrite an existing attribute. The default is' false '.
165
164
 
166
- /** Mixes attributes into classes via decorators
167
- * @param {IObject<any>} params mixed property
168
- * @return {ClassDecorator} Decorator hook function
169
- * * /
165
+ ```javascript
166
+ const target = { a: 1 };
167
+ const source = { b: 2 };
168
+ const result = mixIn(target, source);
169
+ console.log(result); // Output: {a: 1, b: 2}
170
+ ```
170
171
 
171
- export type IClassDecorator = (params: IObject<any>) => <TFunction extends Function>(target: TFunction) => void
172
+ ##### 4. `enumInversion(target: object): object`
172
173
 
173
- /**JSON.parse package
174
- * @param {string} target string
175
- * @return {IObject<any>} object
176
- * * /
174
+ Inverts the key-value pair of an enumeration object.
177
175
 
178
- export type IStringToJson = (target: string) => IObject<any>
176
+ - 'target' : enumeration object to be reversed.
179
177
 
180
- /**JSON.stringify encapsulation
181
- * @param {IObject<any>} target object
182
- * @return {string} A string
183
- * * /
178
+ ```javascript
179
+ const enumObj = { key1: "value1", key2: "value2" };
180
+ const invertedEnum = enumInversion(enumObj);
181
+ console.log(invertedEnum); // Output: {value1: 'key1', value2: 'key2'}
182
+ ```
184
183
 
185
- export type IJsonToString = (target: IObject<any>) => string
184
+ ##### 5. `isNotObject(source: any, type: string): boolean`
186
185
 
187
- ##### function
186
+ Check whether the value is of a non-object type.
188
187
 
189
- /** throttle: A high-frequency event is triggered, but only once in n seconds
190
- * @param {Function} fn Function for throttling
191
- * @param {number} time Execution interval/ms
192
- * @return {Function} Function after processing
193
- * * /
188
+ - 'source' : indicates the value to be checked.
189
+ - 'type' : indicates the data type.
194
190
 
195
- export type IThrottle = (fn: Function, time: number) => (... args: any[]) => void
191
+ ```javascript
192
+ const result = isNotObject(42, "number");
193
+ console.log(result); // Output: false
194
+ ```
196
195
 
197
- /** debounce: The function executes only once within n seconds after a high-frequency event is triggered
198
- * @param {Function} fn Function for anti-shake processing
199
- * @param {number} time Allows running function intervals/milliseconds
200
- * @return {Function} Function after processing
201
- * * /
196
+ ##### 6. `cloneDeep(target: any): any`
202
197
 
203
- export type IDebounce = (fn: Function, time: number) => (... args: any[]) => void
198
+ Deep clone object.
204
199
 
205
- / * *
206
- * Promise flattening to avoid Promise nesting
207
- * @param {number} timer times out
208
- * @returns {Promise,resolve,reject}
209
- * /
210
- export type IDefer = (timer: number) => IPromise
200
+ - 'target' : indicates the object to be cloned.
211
201
 
212
- /**await and try catch catch exception handling methods
213
- * @param {Promise<any>} defer the delay function
214
- * @returns {Promise<any>} [error, result]
215
- * /
202
+ ```javascript
203
+ const obj = { a: { b: { c: 42 } } };
204
+ const clonedObj = cloneDeep(obj);
205
+ console.log(clonedObj); // Output: {a: {b: {c: 42}}}
206
+ ```
216
207
 
217
- export type ICatchAwait<T extends Promise<any>> = (defer: T) => T
208
+ ##### 7. `createObjectVariable(type: string, source: object = {}): object`
218
209
 
219
- ##### array
210
+ Creates an object of a specific type based on its type.
220
211
 
221
- /** The array is out of order
222
- * @param {Array<any>} arr target array
223
- * @returns {Array<any>} The array is out of order
224
- * /
212
+ - 'type' : indicates the type of the object to be created.
213
+ - 'source' : initializes the data of the object.
225
214
 
226
- export type IArrayRandom<T extends any[]> = (arr: T) => T
215
+ ```javascript
216
+ const array = createObjectVariable("array", [1, 2, 3]);
217
+ console.log(array); // Output: [1, 2, 3]
218
+ ```
227
219
 
228
- /** array array weight removal
229
- * @param {Array<any>} arr target array
230
- * @returns {Array<any>} Specifies the array after deduplication
231
- * /
220
+ ##### 8. `createObject(source: object): object`
232
221
 
233
- export type IArrayUniq<T extends any[]> = (arr: T) => T
222
+ Create objects using a prototype chain.
234
223
 
235
- /** Array flattens
236
- * @param {Array<any>} arr target array
237
- * @returns {Array<any>} A flat array
238
- * /
224
+ - 'source' : prototype object.
239
225
 
226
+ ```javascript
227
+ const protoObj = { a: 1 };
228
+ const newObj = createObject(protoObj);
229
+ console.log(newObj.a); // Output: 1
230
+ ```
240
231
 
241
- export type IArrayDemote<T extends IDemoteArray<any>> = (arr: T, result? : T) => T
232
+ ##### 9. `inherit(source: object, target: function): function`
242
233
 
243
- ##### element
234
+ Inherit the prototype chain.
244
235
 
245
- /**IElementParams
246
- * @param {string} ele Label type
247
- * @param {CSSStyleDeclaration} style
248
- * @param {Attr} attr attribute
249
- * @param {object} parent Parent element
250
- * /
236
+ - 'source' : prototype chain of the parent object.
237
+ - 'target' : constructor of the child object.
251
238
 
252
- interface IElementParams<T> {
253
- ele: T | string
254
- style: CSSStyleDeclaration
255
- attr: Attr
256
- parent: T
239
+ ```javascript
240
+ function Parent() {}
241
+ Parent.prototype.method = function () {
242
+ console.log("Hello from parent");
243
+ };
244
+
245
+ function Child() {}
246
+ inherit(Parent, Child);
247
+ const childInstance = new Child();
248
+ childInstance.method(); // Output: Hello from parent
249
+ ```
250
+
251
+ ##### 10. `getInstance(classProto: function, overwrite: boolean = false, ... params: any[]): object`
252
+
253
+ Gets a singleton instance of a class.
254
+
255
+ - 'classProto' : The prototype chain of the class.
256
+ - 'overwrite' : Whether to overwrite an existing instance. The default is' false '.
257
+ - 'params' : arguments to the class constructor.
258
+
259
+ ```javascript
260
+ class Singleton {
261
+ constructor(name) {
262
+ this.name = name;
263
+ }
257
264
  }
258
265
 
259
- /** Add labels, set properties and styles
260
- * @param {IElementParams} params configuration
261
- * @return {ElementObject} Generated label
262
- * /
266
+ const instance1 = getInstance(Singleton, false, "Instance 1");
267
+ const instance2 = getInstance(Singleton, true, "Instance 2");
263
268
 
264
- export type ICreateElement<T = HTMLElement> = (params: IElementParams<T>) => T
269
+ console.log(instance1 === instance2); // Output: false
270
+ ```
265
271
 
266
- ##### event
272
+ ##### 11. `classDecorator(params: object): ClassDecorator`
267
273
 
268
- /** Browser events
269
- * @param {Document} ele tag
270
- * @param {string} type Event type
271
- * @param {(e: Event) => void} handler Event callback
272
- * @return {void}
273
- * /
274
+ Add a decorator to the class.
274
275
 
275
- export type IAddHandler = <T extends Document>(ele: T, type: string, handler: (e: Event) => void) => void
276
+ - 'params' : properties and methods to add.
276
277
 
277
- /** Cancel event bubbling
278
- * @param {Event} e Browser event object
279
- * @return {void}
280
- * /
278
+ ```javascript
279
+ @classDecorator({
280
+ additionalMethod: function () {
281
+ console.log("Additional method");
282
+ },
283
+ })
284
+ class DecoratedClass {}
281
285
 
282
- export type IStopBubble = (e: Event) => void
286
+ const instance = new DecoratedClass();
287
+ instance.additionalMethod(); // Output: Additional method
288
+ ```
283
289
 
284
- /** Cancels the default event
285
- * @param {Event} e Browser event object
286
- * @return {void}
287
- * /
290
+ ##### 12. `stringToJson(target: string): object | null`
288
291
 
289
- export type IStopDefault = (e: Event) => void
292
+ Converts a JSON string to an object.
290
293
 
291
- /** Cancels browser events
292
- * @param {Document} ele tag
293
- * @param {string} type Event type
294
- * @param {(e: Event) => void} handler Event callback
295
- * @return {void}
296
- * /
294
+ - 'target' : JSON string to be converted.
297
295
 
298
- export type IRemoveHandler = <T extends Document>(ele: T, type: string, handler: (e: Event) => void) => void
296
+ ```javascript
297
+ const jsonString = '{"key": "value"}';
298
+ const jsonObject = stringToJson(jsonString);
299
+ console.log(jsonObject); // Output: {key: 'value'}
300
+ ```
299
301
 
300
- /** Cancels the default event
301
- * @param {Event} e Browser event object
302
- * @return {void}
303
- * /
302
+ ##### 13. `jsonToString(target: any): string`
304
303
 
305
- export type IDispatchEvent = <T extends Document>(ele: T, data: any) => void
304
+ Converts the object to a JSON string.
306
305
 
306
+ - 'target' : indicates the object to be converted.
307
307
 
308
- ##### log
308
+ ```javascript
309
+ const obj = { key: "value" };
310
+ const jsonString = jsonToString(obj);
311
+ console.log(jsonString); // Output: '{"key":"value"}'
312
+ ```
309
313
 
310
- /** Single line output
311
- * @param {string} str Output character
312
- * @param {boolean} overwrite overwrites the previous output
313
- * @param {boolean} warp Wrap the last line
314
- * @return {void}
315
- * /
316
- export type ILogOneLine = (str: string, overwrite? : boolean, warp? : boolean) => void
314
+ ##### 14. `isWindow(win: any): boolean`
317
315
 
318
- /** Loops out a queue
319
- * @param {string[]} loopList Indicates the output character queue
320
- * @param {number} index The number of characters
321
- * @param {boolean} isStop Control pause loop
322
- * @param {number} timer Indicates two interval times
323
- * /
324
- export type ILogLoopParams = {
325
- loopList? : string[]
326
- index? : number
327
- isStop? : boolean
328
- timer? : number
329
- }
330
- export type ILogLoop = (opts? : ILogLoopParams) => ILogLoopParams | void
316
+ Check whether it is a browser window.
331
317
 
332
- ##### request module
333
- ###### https://gitee.com/DieHunter/js-request-lib
334
- export type IRequestParams<T> = T | IObject<any> | null
318
+ - 'win' : indicates the object to be checked.
335
319
 
336
- // Request path
320
+ ```javascript
321
+ const isBrowserWindow = isWindow(window);
322
+ console.log(isBrowserWindow); // Output: true
323
+ ```
337
324
 
338
- export type IUrl = string
325
+ #### array module
339
326
 
340
- // Environmental judgment
327
+ ##### 1. `arrayRandom(arr: any[]): any[]`
341
328
 
342
- export type IEnv = 'Window' | 'Node'
329
+ Randomly sort the array.
343
330
 
344
- // fetch Returns the value
331
+ - 'arr' : array to sort.
345
332
 
346
- export type IDataType = "text" | "json" | "blob" | "formData" | "arrayBuffer"
333
+ ```javascript
334
+ const originalArray = [1, 2, 3, 4, 5];
335
+ const randomizedArray = arrayRandom(originalArray);
336
+ console.log(randomizedArray);
337
+ // Output: a randomly sorted array
338
+ ```
347
339
 
348
- // Request mode
340
+ ##### 2. `arrayUniq(arr: any[]): any[]`
349
341
 
350
- export type IRequestMethods = "GET" | "POST" | "DELETE" | "PUT" | "OPTION"
342
+ Removes duplicate elements from the array.
351
343
 
352
- // body structure
344
+ - 'arr' : array to process.
353
345
 
354
- export type IRequestBody = IRequestParams<BodyInit>
346
+ ```javascript
347
+ const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
348
+ const uniqueArray = arrayUniq(arrayWithDuplicates);
349
+ console.log(uniqueArray);
350
+ // Output: Array with duplicate elements removed
351
+ ```
355
352
 
356
- // heads structure
353
+ ##### 3. `arrayDemote(arr: IDemoteArray<any>, result: any[] = []): any[]`
357
354
 
358
- export type IRequestHeaders = IRequestParams<HeadersInit>
355
+ Reduces the dimension of multiple nested arrays.
359
356
 
360
- // Request the base function
357
+ - 'arr' : array to be reduced.
358
+ - 'result' : The array used to store the result. The default is an empty array.
361
359
 
362
- export type IRequestBaseFn = (url: IUrl, opts: IRequestOptions) => Promise<any>
360
+ ```javascript
361
+ const nestedArray = [1, [2, [3, [4]], 5]];
362
+ const demotedArray = arrayDemote(nestedArray);
363
+ console.log(demotedArray);
364
+ // Output: reduced array [1, 2, 3, 4, 5]
365
+ ```
363
366
 
364
- // Request function body
367
+ #### function module
365
368
 
366
- export type IRequestFn = (url? : IUrl, query? : IObject<any>, body? : IRequestBody, opts? : IRequestOptions) => Promise<any>
369
+ ##### 1. `throttle(fn: Function, time: number): Function`
367
370
 
368
- // Request parameters
371
+ Limits how often a function is called within a specified period of time.
369
372
 
370
- export type IRequestOptions = {
371
- method? : IRequestMethods
372
- query? : IRequestParams<IObject<any>>
373
- body? : IRequestBody
374
- headers? : IRequestHeaders
375
- controller? : AbortController
376
- timeout? : number
377
- timer? : number | unknown | null
378
- [key: string]: any
379
- }
373
+ - 'fn' : function to be executed.
374
+ - 'time' : indicates the time interval (milliseconds).
380
375
 
381
- // Interceptor
376
+ ```javascript
377
+ const throttledFunction = throttle(
378
+ () => console.log("Throttled function called!"),
379
+ 1000
380
+ );
381
+ throttledFunction(); // This command is executed only after 1 second
382
+ ```
382
383
 
383
- export type IInterceptors = {
384
- use(type: "request" | "response" | "error", fn: Function): void
385
- get reqFn(): Function
386
- get resFn(): Function
387
- get errFn(): Function
388
- }
384
+ ##### 2. `debounce(fn: Function, time: number): Function`
389
385
 
390
- // Public function
391
-
392
- export type IRequestBase = {
393
- readonly origin: string
394
- chackUrl: (url: IUrl) => boolean
395
- envDesc: () => IEnv
396
- errorFn: <Err = any, R = Function>(reject: R) => (err: Err) => R
397
- clearTimer: (opts: IRequestOptions) => void
398
- initAbort: <T = IRequestOptions>(opts: T) => T
399
- requestType: () => IRequestBaseFn
400
- fixOrigin: (fixStr: string) => string
401
- fetch: IRequestBaseFn
402
- http: IRequestBaseFn
403
- getDataByType: (type: IDataType, response: Response) => Promise<any>
404
- }
386
+ Limits the continuous invocation of a function for a specified period of time.
405
387
 
406
- // Initialize parameters
388
+ - 'fn' : function to be executed.
389
+ - 'time' : indicates the time interval (milliseconds).
407
390
 
408
- export type IRequestInit = {
409
- initDefaultParams: (url: IUrl, opts: IRequestOptions) => any
410
- initFetchParams: (url: IUrl, opts: IRequestOptions) => any
411
- initHttpParams: (url: IUrl, opts: IRequestOptions) => any
412
- }
391
+ ```javascript
392
+ const debouncedFunction = debounce(
393
+ () => console.log("Debounced function called!"),
394
+ 1000
395
+ );
396
+ debouncedFunction(); // Called multiple times within 1 second, only the last time will be executed
397
+ ```
413
398
 
414
- // Request principal class
399
+ ##### 3. `defer(timer: number = 0): { promise: Promise<void>, resolve: Function, reject: Function }`
415
400
 
416
- export type IRequest = {
417
- GET: IRequestFn
418
- POST: IRequestFn
419
- DELETE: IRequestFn
420
- PUT: IRequestFn
421
- OPTIONS: IRequestFn
422
- HEAD: IRequestFn
423
- PATCH: IRequestFn
424
- } & IRequestBase
401
+ Create a flat Promise delay object that can be set to time out after a certain amount of time.
425
402
 
403
+ - 'timer' : indicates the timeout period (milliseconds). The default value is 0.
426
404
 
427
- <! -- News Center -->
428
- ##### News Center
429
- ###### https://gitee.com/DieHunter/message-center
430
- export declare interface Handlers {
431
- [key: string]: Array<Function>
432
- }
433
- export declare interface IMessageCenter {
434
- events: Handlers
435
- _instance? : IMessageCenter
436
- on: (type: string, handler: Function) => this
437
- emit: (type: string, data? : any) => this
438
- un: (type: string, handler? : Function) => this
439
- once: (type: string, handler: Function) => this
440
- clear: () => this
441
- has: (type: string) => boolean
442
- handlerLength: (type: string) => number
443
- watch: (type: string, handler: Function) => this
444
- invoke: (type: string, data? : any) => Promise<void>
445
- }
405
+ ```javascript
406
+ const deferFn = () => {
407
+ const { resolve, promise } = defer();
408
+ setTimeout(() => resolve("success"), 500);
409
+ return promise;
410
+ };
411
+ const delayFn = () => {
412
+ const { promise } = defer(1000);
413
+ return promise;
414
+ };
415
+ deferFn().then(console.log); // Delay output
416
+ delayFn().catch(console.error); // Timeout output
417
+ ```
446
418
 
419
+ ##### 4. `catchAwait(defer: Promise<any>): Promise<[Error | null, any]>`
447
420
 
448
- <! -- Task Queue -->
449
- ##### Task queue
450
- ###### https://gitee.com/DieHunter/task-queue
451
- / * *
452
- * Single queue
453
- * defer: asynchronous function to be run
454
- * params? The: defer parameter can also be passed directly using bind
455
- *
456
- * /
457
- export interface IQueue {
458
- defer: Function
459
- name? : string
460
- }
461
- / * *
462
- * Queue parameter
463
- * children: Queue list
464
- * name: indicates the unique identifier of the queue
465
- * result: indicates the result after the run is complete
466
- *
467
- * /
468
- export interface IQueues {
469
- children: Array<Function>
470
- name: string
471
- result? : any[]
472
- }
473
- / * *
474
- * queue cache
475
- * /
476
- export type IQueueTemp = {
477
- [key: string]: IQueues
478
- }
479
- / * *
480
- * System queue
481
- * /
482
- export type IQueueList = Array<IQueue>
483
- / * *
484
- * The queue status idle: idle pending: waiting fulfilled: completed rejected: failed
485
- * /
486
- export type IState = "idle" | "pending" | "fulfilled" | "rejected"
487
- / * *
488
- * Task queue parameters
489
- * /
490
- export type ITaskQueueProps = {
491
- maxLen: number
492
- }
493
- / * *
494
- * Task queue
495
- * /
496
- export type ITaskQueue = {
497
- readonly fix: string
498
- props: ITaskQueueProps
499
- queueTemp: IQueueTemp
500
- queues: IQueueList
501
- state: IState
502
- push: (queue: IQueues) => Promise<void>
503
- unshift: (length: number) => IQueueList
504
- run: (reject: any) => unknown
505
- clear: () => void
506
- }
421
+ Catches an Error for an asynchronous operation and returns' [Error, null] 'or' [null, result] '.
507
422
 
423
+ - 'defer' : The Promise object for the asynchronous operation.
508
424
 
425
+ ```javascript
426
+ const asyncOperation = new Promise((resolve, reject) => {
427
+ // Simulate asynchronous operations
428
+ setTimeout(() => {
429
+ reject(new Error("Something went wrong!"));
430
+ }, 1000);
431
+ });
509
432
 
510
- /** Single line output
511
- * @param {string} str Output character
512
- * @param {boolean} overwrite overwrites the previous output
513
- * @param {boolean} warp Wrap the last line
514
- * @return {void}
515
- * /
516
- export function logOneLine(str: string): void
517
- export function logOneLine(str: string, overwrite? : boolean): void
518
- export function logOneLine(str: string, overwrite? : boolean, warp? : boolean): void
519
-
520
-
521
- // animate
522
-
523
- / * *
524
- * Animation
525
- * reference: https://gitee.com/DieHunter/myCode/tree/master/%E5%89%8D%E7%AB%AF%E5%8A%A8%E7%94%BB/js
526
- *
527
- * /
528
- export type IAnimateFrame = {
529
- id: number | null // Animation index
530
- duration: number // Frame number control
531
- isActive: boolean// Activate control
532
- fn(timer: number): void
533
- start(duration: number): void
534
- stop(): void
535
- animate(timer: number): void
536
- }
537
- declare var IAnimateFrame: {
538
- new(fn: (timer: number) => void): IAnimateFrame
539
- prototype: IAnimateFrame
540
- }
433
+ const [error, result] = await catchAwait(asyncOperation);
434
+ console.log(error); // Output: Error: Something went wrong!
435
+ console.log(result); // Output: null
436
+ ```
437
+
438
+ #### element module
439
+
440
+ ##### 1. `createElement(options: { ele? : string | HTMLElement, style? : object, attr? : object, parent? : HTMLElement }): HTMLElement`
441
+
442
+ Creates and returns an HTML element.
443
+
444
+ - 'ele' : element type or existing HTMLElement object, optional, default is 'div'.
445
+ - 'style' : The style object of the element, optional.
446
+ - 'attr' : attribute object of the element, optional.
447
+ - 'parent' : indicates the parent of the element. This parameter is optional.
448
+
449
+ ```javascript
450
+ const options = {
451
+ ele: "div",
452
+ style: { color: "blue", fontSize: "16px" },
453
+ attr: { id: "myElement", className: "custom-class" },
454
+ parent: document.body,
455
+ };
456
+
457
+ const createdElement = createElement(options);
458
+ // Create a div element with style and attributes in the body
459
+ ```
460
+
461
+ #### event module
462
+
463
+ ##### 1. `addHandler(ele: HTMLElement, type: string, handler: EventListener): void`
464
+
465
+ Add event listeners to the element.
466
+
467
+ - 'ele' : target element.
468
+ - 'type' : indicates the type of the event.
469
+ - 'handler' : event handler.
470
+
471
+ ```javascript
472
+ const button = document.getElementById("myButton");
473
+ const handleClick = () => console.log("Button clicked! ");
474
+ addHandler(button, "click", handleClick);
475
+ ```
476
+
477
+ ##### 2. `stopBubble(event: Event): void`
478
+
479
+ Prevent events from bubbling.
480
+
481
+ - 'event' : indicates an event object.
482
+
483
+ ```javascript
484
+ const handleClick = (event) => {
485
+ console.log("Button clicked! ");
486
+ stopBubble(event);
487
+ };
488
+ ```
489
+
490
+ ##### 3. `stopDefault(event: Event): void`
491
+
492
+ Default behavior to block events.
493
+
494
+ - 'event' : indicates an event object.
495
+
496
+ ```javascript
497
+ const handleFormSubmit = (event) => {
498
+ console.log("Form submitted! ");
499
+ stopDefault(event);
500
+ };
501
+ ```
502
+
503
+ ##### 4. `removeHandler(ele: HTMLElement, type: string, handler: EventListener): void`
504
+
505
+ Removes an element's event listener.
506
+
507
+ - 'ele' : target element.
508
+ - 'type' : indicates the type of the event.
509
+ - 'handler' : event handler to be removed.
510
+
511
+ ```javascript
512
+ const button = document.getElementById("myButton");
513
+ const handleClick = () => console.log("Button clicked! ");
514
+ addHandler(button, "click", handleClick);
515
+ // Other operations...
516
+ removeHandler(button, "click", handleClick);
517
+ ```
518
+
519
+ ##### 5. `dispatchEvent(ele: HTMLElement, data: any): void`
520
+
521
+ Trigger a custom event.
522
+
523
+ - 'ele' : target element.
524
+ - 'data' : indicates the data of a custom event.
525
+
526
+ ```javascript
527
+ const customEvent = new CustomEvent("customEvent", {
528
+ detail: { key: "value" },
529
+ });
530
+ const targetElement = document.getElementById("myElement");
531
+ dispatchEvent(targetElement, customEvent);
532
+ ```
533
+
534
+ #### storage module
535
+
536
+ ##### 1. `setStorage(key: string, val: any): void`
537
+
538
+ Store values to local storage.
539
+
540
+ - 'key' : specifies the name of the key.
541
+ - 'val' : The value to be stored.
542
+
543
+ ```javascript
544
+ const userData = { username: "john_doe", email: "john@example.com" };
545
+ setStorage("user_data", userData);
546
+ ```
547
+
548
+ ##### 2. `getStorage(key: string): any`
549
+
550
+ Gets the value from local storage.
551
+
552
+ - 'key' : specifies the key name to be obtained.
553
+
554
+ ```javascript
555
+ const storedUserData = getStorage("user_data");
556
+ console.log(storedUserData);
557
+ // Output: {username: 'john_doe', email: 'john@example.com'}
558
+ ```
559
+
560
+ ##### 3. `clearStorage(key? : string): void`
561
+
562
+ Clear the value from the local store.
563
+
564
+ - 'key' : specifies the name of the key to be cleared. If no key name is provided, all storage is cleared.
565
+
566
+ ```javascript
567
+ clearStorage("user_data"); // Clear the stored value for a specific key name
568
+ // or
569
+ clearStorage(); // Clear all locally stored values
570
+ ```
571
+
572
+ #### log module
573
+
574
+ ##### 1. `logOneLine(str: string, overwrite: boolean = false, wrap: boolean = true): void`
575
+
576
+ Output logs in one line.
577
+
578
+ - 'str' : The string to be output.
579
+ - 'overwrite' : Whether to overwrite the current line. The default is' false '.
580
+ - 'wrap' : Whether to wrap lines after output, defaults to 'true'.
581
+
582
+ ```javascript
583
+ logOneLine("This is a single line log message.");
584
+ ```
585
+
586
+ ##### 2. `logLoop(opts? : { loopList? : string[], isStop? : boolean, timer? : number, index? : number }): { loopList? : string[], isStop? : boolean, timer? : number, index? : number }`
587
+
588
+ Output a loop animation in the console.
589
+
590
+ - 'opts' : an optional parameter object containing the following properties:
591
+ - `loopList` : animation character list, the default is `[' \ \ ', '|', '/', '-', '-']`.
592
+ - 'isStop' : Whether to stop the loop. The default is' false '.
593
+ - 'timer' : Animation switch interval (milliseconds), default is' 100 '.
594
+ - 'index' : indicates the index of the current animated character. The default value is 0.
595
+
596
+ ```javascript
597
+ logLoop(); // Start the default loop animation
598
+ // or
599
+ logLoop({ loopList: ["-", "+", "-", "+"], timer: 200 }); // Start a custom loop animation
600
+ ```
601
+
602
+ #### animation module
603
+
604
+ ##### 1. `class AnimateFrame`
605
+
606
+ A class that provides frame animation.
607
+
608
+ - `start(duration? : number): void ': Starts frame animation, optional parameter' duration 'is frame number control.
609
+ - 'stop(): void' : stops frame animation.
610
+
611
+ ```javascript
612
+ const animateFrame = new AnimateFrame((timestamp) => {
613
+ // Update animation status here
614
+ console.log("AnimationFrame callback:", timestamp);
615
+ });
616
+
617
+ animateFrame.start(60); // Start frame animation at 60 frames per second
618
+ // Other operations...
619
+ animateFrame.stop(); // Stop frame animation
620
+ ```
621
+
622
+ ##### 2. `quadraticBezier(_x: number, _y: number, t: number): [number, number]`
623
+
624
+ Calculate the coordinates of points on the quadratic Bessel curve.
625
+
626
+ - '\_x' : x coordinates of control point 1.
627
+ - '\_y' : y coordinate of control point 1.
628
+ - 't' : indicates the time parameter. The value ranges from 0 to 1.
629
+
630
+ ```javascript
631
+ const result = quadraticBezier(0, 0, 1, 1, 0.5);
632
+ console.log(result);
633
+ // Output: [0.75, 0.75]
634
+ ```
635
+
636
+ ##### 3. `cubicBezier(_x1: number, _y1: number, _x2: number, _y2: number, t: number): [number, number]`
637
+
638
+ Calculate the coordinates of points on a cubic Bezier curve.
639
+
640
+ - '\_x1' : x coordinate of control point 1.
641
+ - '\_y1' : y coordinate of control point 1.
642
+ - '\_x2' : control point 2 x coordinates.
643
+ - '\_y2' : y coordinate of control point 2.
644
+ - 't' : indicates the time parameter. The value ranges from 0 to 1.
645
+
646
+ ```javascript
647
+ const result = cubicBezier(0, 0, 0.5, 1, 0.5);
648
+ console.log(result);
649
+ // Output: [0.375, 0.625]
650
+ ```
651
+
652
+ ##### 4. `factorial(n: number): number`
653
+
654
+ Calculate the factorial.
655
+
656
+ - n: indicates a non-negative integer.
657
+
658
+ ```javascript
659
+ const result = factorial(5);
660
+ console.log(result);
661
+ // Output: 120
662
+ ```
663
+
664
+ ##### 5. `combination(n: number, k: number): number`
665
+
666
+ Calculate the number of combinations.
667
+
668
+ - n: indicates the total number.
669
+ - 'k' : indicates the number of selected items.
670
+
671
+ ```javascript
672
+ const result = combination(5, 2);
673
+ console.log(result);
674
+ // Output: 10
675
+ ```
676
+
677
+ ##### 6. `NBezier(points: number[][], t: number): [number, number]`
678
+
679
+ Calculate the point coordinates on the NTH Bezier curve.
680
+
681
+ - 'points' : array of control points. Each point is a second-order array.
682
+ - 't' : indicates the time parameter. The value ranges from 0 to 1.
683
+
684
+ ```javascript
685
+ const points = [
686
+ [0, 0],
687
+ [1, 1],
688
+ [2, 0],
689
+ ];
690
+ const result = NBezier(points, 0.5);
691
+ console.log(result);
692
+ // Output: [1.5, 0.75]
693
+ ```
694
+
695
+ #### event-message-center
696
+
697
+ https://gitee.com/DieHunter/message-center
698
+
699
+ #### task-queue-lib
700
+
701
+ https://gitee.com/DieHunter/task-queue
702
+
703
+ #### js-request-lib
704
+
705
+ https://gitee.com/DieHunter/js-request-lib