utils-lib-js
Version:
JavaScript工具函数,封装的一些常用的js函数
792 lines (556 loc) • 21.2 kB
Markdown
# utils-lib-js
## Introduction
JavaScript utility functions, packaging some commonly used js functions
## Debugging instructions
1. pnpm build
2. pnpm debug (debug source)
3. Import the tool library in esm, cjs, and window environments
## Contribute
1. Fork the local warehouse
2. Star Warehouse
3. Submit the code
4. Create a Pull Request
## Instructions for use
### Install
`npm install utils-lib-js`
or
`yarn add utils-lib-js`
or
`pnpm install utils-lib-js`
### Introduce
#### ESM
```javascript
import { defer, messageCenter, TaskQueue, Request } from "utils-lib-js";
```
#### CJS
```javascript
const { defer, messageCenter, TaskQueue } = require("utils-lib-js");
```
#### in your browser
```html
<script src="./node_modules/utils-lib-js/dist/umd/index.js"></script>
<script>
console.log(UtilsLib);
</script>
```
### TS interface comment
With reference to https://gitee.com/DieHunter/utils-lib-js/blob/master/src/types.ts
### Code demo
#### base module
##### 1. `randomNum(min: number, max: number, bool? : boolean): number`
Generates random integers within the specified range.
- `min` : indicates the minimum value (including).
- `max` : indicates the maximum value (inclusive).
- `bool` : Indicates whether the maximum value is contained. The default value is false.
```javascript
const randomNumber = randomNum(1, 10);
console.log(randomNumber); // Generates a random integer between 1 and 10
```
##### 2. `urlSplit(url: string): object`
Parses URL query parameters into objects.
- `url` : indicates the URL containing the query parameter.
```javascript
const url = "https://example.com/path?param1=value1¶m2=value2";
const params = urlSplit(url);
console.log(params);
// Output: {param1: 'value1', param2: 'value2'}
```
##### 3. `urlJoin(url: string, query: object): string`
Converts the object to a URL query parameter and concatenates it with the original URL.
- `url` : indicates the original URL.
- `query` : object containing query parameters.
```javascript
const url = "https://example.com/path";
const query = { param1: "value1", param2: "value2" };
const newUrl = urlJoin(url, query);
console.log(newUrl);
// Output: https://example.com/path?param1=value1¶m2=value2
```
##### 4. `getType(data: any): string`
Get the type of data.
- `data` : indicates the data to be checked.
```javascript
const dataType = getType("Hello, World!");
console.log(dataType); // Output: string
```
##### 5. `getTypeByList(data: any, whiteList: string[]): boolean`
Check whether the data type is in the whitelist.
- `data` : indicates the data to be checked.
- `whiteList` : indicates the list of allowed data types.
```javascript
const data = 42;
const allowedTypes = ["number", "string"];
const isTypeAllowed = getTypeByList(data, allowedTypes);
console.log(isTypeAllowed); // Output: true
```
##### 6. `toKebabCase(camelCase: string, separator: string = "-"): string`
The hump name is converted to a hyphenated name
- `camelCase` : hump type variable
- `separator` : indicates the separator
```javascript
const camelCase = "fontSize";
const kebabCase = toKebabCase(camelCase);
console.log(kebabCase); // Output: font-size
```
#### object module
##### 1. `getValue(object: object, key: string, defaultValue: any = ''): any`
Gets the value of the specified path in the object.
- `object` : indicates the target object.
- `key` : the path to the value to be obtained.
- `defaultValue` : Default value, returned if the path does not exist.
```javascript
const obj = { a: { b: { c: 42 } } };
const value = getValue(obj, "a.b.c", "default");
console.log(value); // Output: 42
```
##### 2. `setValue(object: object, key: string, value: any = {}): object`
Sets the value of the specified path in the object.
- `object` : indicates the target object.
- `key` : path to the value to be set.
- `value` : indicates the value to be set.
```javascript
const obj = { a: { b: { c: 42 } } };
setValue(obj, "a.b.d", "new value");
console.log(obj); // Output: {a: {b: {c: 42, d: 'new value'}}}
```
##### 3. `mixIn(target: object, source: object = {}, overwrite: boolean = false): object`
Mixes the properties of the source object into the target object.
- `target` : indicates the target object.
- `source` : indicates the source object.
- `overwrite` : Whether to overwrite an existing attribute. The default is' false '.
```javascript
const target = { a: 1 };
const source = { b: 2 };
const result = mixIn(target, source);
console.log(result); // Output: {a: 1, b: 2}
```
##### 4. `enumInversion(target: object): object`
Inverts the key-value pair of an enumeration object.
- `target` : enumeration object to be reversed.
```javascript
const enumObj = { key1: "value1", key2: "value2" };
const invertedEnum = enumInversion(enumObj);
console.log(invertedEnum); // Output: {value1: 'key1', value2: 'key2'}
```
##### 5. `isNotObject(source: any, type: string): boolean`
Check whether the value is of a non-object type.
- `source` : indicates the value to be checked.
- `type` : indicates the data type.
```javascript
const result = isNotObject(42, "number");
console.log(result); // Output: false
```
##### 6. `cloneDeep(target: any): any`
Deep clone object.
- `target` : indicates the object to be cloned.
```javascript
const obj = { a: { b: { c: 42 } } };
const clonedObj = cloneDeep(obj);
console.log(clonedObj); // Output: {a: {b: {c: 42}}}
```
##### 7. `createObjectVariable(type: string, source: object = {}): object`
Creates an object of a specific type based on its type.
- `type` : indicates the type of the object to be created.
- `source` : initializes the data of the object.
```javascript
const array = createObjectVariable("array", [1, 2, 3]);
console.log(array); // Output: [1, 2, 3]
```
##### 8. `createObject(source: object): object`
Create objects using a prototype chain.
- `source` : prototype object.
```javascript
const protoObj = { a: 1 };
const newObj = createObject(protoObj);
console.log(newObj.a); // Output: 1
```
##### 9. `inherit(source: object, target: function): function`
Inherit the prototype chain.
- `source` : prototype chain of the parent object.
- `target` : constructor of the child object.
```javascript
function Parent() {}
Parent.prototype.method = function () {
console.log("Hello from parent");
};
function Child() {}
inherit(Parent, Child);
const childInstance = new Child();
childInstance.method(); // Output: Hello from parent
```
##### 10. `getInstance(classProto: function, overwrite: boolean = false, ... params: any[]): object`
Gets a singleton instance of a class.
- `classProto` : The prototype chain of the class.
- `overwrite` : Whether to overwrite an existing instance. The default is' false '.
- `params` : arguments to the class constructor.
```javascript
class Singleton {
constructor(name) {
this.name = name;
}
}
const instance1 = getInstance(Singleton, false, "Instance 1");
const instance2 = getInstance(Singleton, true, "Instance 2");
console.log(instance1 === instance2); // Output: false
```
##### 11. `classDecorator(params: object): ClassDecorator`
Add a decorator to the class.
- `params` : properties and methods to add.
```javascript
@classDecorator({
additionalMethod: function () {
console.log("Additional method");
},
})
class DecoratedClass {}
const instance = new DecoratedClass();
instance.additionalMethod(); // Output: Additional method
```
##### 12. `stringToJson(target: string): object | null`
Converts a JSON string to an object.
- `target` : JSON string to be converted.
```javascript
const jsonString = '{"key": "value"}';
const jsonObject = stringToJson(jsonString);
console.log(jsonObject); // Output: {key: 'value'}
```
##### 13. `jsonToString(target: any): string`
Converts the object to a JSON string.
- `target` : indicates the object to be converted.
```javascript
const obj = { key: "value" };
const jsonString = jsonToString(obj);
console.log(jsonString); // Output: '{"key":"value"}'
```
##### 14. `isWindow(win: any): boolean`
Check whether it is a browser window.
- `win` : indicates the object to be checked.
```javascript
const isBrowserWindow = isWindow(window);
console.log(isBrowserWindow); // Output: true
```
##### 14. `emptyObject(init: IObject): object`
Creates an object whose prototype is empty.
- `init` : initializes the object.
```javascript
const o = emptyObject({ name: "hunter" });
const o2 = { name: "hunter" };
console.log(o.__proto__, o2.__proto__); // Output: undefined, [Object: null prototype] {}
```
##### 15. `isEmptyObject(object: IObject<unknown>): boolean`
Determines if the object is empty
- `object` : the target object.
```javascript
const o = isEmptyObject({ name: "a u" });
const o2 = isEmptyObject({});
console.log(o, o2); // Output: false true
```
#### array module
##### 1. `arrayRandom(arr: any[]): any[]`
Randomly sort the array.
- `arr` : array to sort.
```javascript
const originalArray = [1, 2, 3, 4, 5];
const randomizedArray = arrayRandom(originalArray);
console.log(randomizedArray);
// Output: a randomly sorted array
```
##### 2. `arrayUniq(arr: any[]): any[]`
Removes duplicate elements from the array.
- `arr` : array to process.
```javascript
const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = arrayUniq(arrayWithDuplicates);
console.log(uniqueArray);
// Output: Array with duplicate elements removed
```
##### 3. `arrayDemote(arr: IDemoteArray<any>, result: any[] = []): any[]`
Reduces the dimension of multiple nested arrays.
- `arr` : array to be reduced.
- `result` : The array used to store the result. The default is an empty array.
```javascript
const nestedArray = [1, [2, [3, [4]], 5]];
const demotedArray = arrayDemote(nestedArray);
console.log(demotedArray);
// Output: reduced array [1, 2, 3, 4, 5]
```
##### 4. arrayLoop(list: any[], current? : number): { item: any; current: number }
Walks through the elements in the group and returns the current element and its index.
- 'list' : The array to traverse.
- 'current' : indicates the index of the current element. The default is 0.
```javascript
// Each time the arrayLoop function is called, current is incremented by 1 and takes the module length to loop to the beginning of the array.
const list = [
" Element 1",
"element 2",
" element 3",
"element 4",
" element 5",
];
// Simulation loop multiple times
let c = 0;
Array(10)
.fill("")
.forEach(() => {
const { item, current } = arrayLoop(list, c);
c = current;
console.log(item, c); // 1,2,3,4,0,1,2,3,4,0
});
```
#### function module
##### 1. `throttle(fn: Function, time: number): Function`
Limits how often a function is called within a specified period of time.
- `fn` : function to be executed.
- `time` : indicates the time interval (milliseconds).
```javascript
const throttledFunction = throttle(
() => console.log("Throttled function called!"),
1000
);
throttledFunction(); // This command is executed only after 1 second
```
##### 2. `debounce(fn: Function, time: number): Function`
Limits the continuous invocation of a function for a specified period of time.
- `fn` : function to be executed.
- `time` : indicates the time interval (milliseconds).
```javascript
const debouncedFunction = debounce(
() => console.log("Debounced function called!"),
1000
);
debouncedFunction(); // Called multiple times within 1 second, only the last time will be executed
```
##### 3. `defer(timer: number = 0): { promise: Promise<void>, resolve: Function, reject: Function }`
Create a flat Promise delay object that can be set to time out after a certain amount of time.
- `timer` : indicates the timeout period (milliseconds). The default value is 0.
```javascript
const deferFn = () => {
const { resolve, promise } = defer();
setTimeout(() => resolve("success"), 500);
return promise;
};
const delayFn = () => {
const { promise } = defer(1000);
return promise;
};
deferFn().then(console.log); // Delay output
delayFn().catch(console.error); // Timeout output
```
##### 4. `catchAwait(defer: Promise<any>): Promise<[Error | null, any]>`
Catches an Error for an asynchronous operation and returns' [Error, null] 'or' [null, result] '.
- `defer` : The Promise object for the asynchronous operation.
```javascript
const asyncOperation = new Promise((resolve, reject) => {
// Simulate asynchronous operations
setTimeout(() => {
reject(new Error("Something went wrong!"));
}, 1000);
});
const [error, result] = await catchAwait(asyncOperation);
console.log(error); // Output: Error: Something went wrong!
console.log(result); // Output: null
```
##### 5. `requestFrame(callback: (timestamp: number) => void, delay? : number): () => void`
Custom frame callbacks for use in browsers and Node.js environments (like setinterval)
- callback: callback function to be executed in each frame, receiving a parameter timestamp indicating the current timestamp.
- delay (optional) : specifies the interval (milliseconds) between each callback execution. The default value is 0.
````javascript
let count = 0;
const clear = requestFrame(() => {
console.log(count);
count++;
if (count === 5) {
clear(); // Cancel the execution
}
}, 1000);
```
#### element module
##### 1. `createElement(options: { ele? : string | HTMLElement, style? : object, attr? : object, parent? : HTMLElement }): HTMLElement`
Creates and returns an HTML element.
- `ele` : element type or existing HTMLElement object, optional, default is 'div'.
- `style` : The style object of the element, optional.
- `attr` : attribute object of the element, optional.
- `parent` : indicates the parent of the element. This parameter is optional.
```javascript
const options = {
ele: "div",
style: { color: "blue", fontSize: "16px" },
attr: { id: "myElement", className: "custom-class" },
parent: document.body,
};
const createdElement = createElement(options);
// Create a div element with style and attributes in the body
````
#### event module
##### 1. `addHandler(ele: HTMLElement, type: string, handler: EventListener): void`
Add event listeners to the element.
- `ele` : target element.
- `type` : indicates the type of the event.
- `handler` : event handler.
```javascript
const button = document.getElementById("myButton");
const handleClick = () => console.log("Button clicked! ");
addHandler(button, "click", handleClick);
```
##### 2. `stopBubble(event: Event): void`
Prevent events from bubbling.
- `event` : indicates an event object.
```javascript
const handleClick = (event) => {
console.log("Button clicked! ");
stopBubble(event);
};
```
##### 3. `stopDefault(event: Event): void`
Default behavior to block events.
- `event` : indicates an event object.
```javascript
const handleFormSubmit = (event) => {
console.log("Form submitted! ");
stopDefault(event);
};
```
##### 4. `removeHandler(ele: HTMLElement, type: string, handler: EventListener): void`
Removes an element's event listener.
- `ele` : target element.
- `type` : indicates the type of the event.
- `handler` : event handler to be removed.
```javascript
const button = document.getElementById("myButton");
const handleClick = () => console.log("Button clicked! ");
addHandler(button, "click", handleClick);
// Other operations...
removeHandler(button, "click", handleClick);
```
##### 5. `dispatchEvent(ele: HTMLElement, data: any): void`
Trigger a custom event.
- `ele` : target element.
- `data` : indicates the data of a custom event.
```javascript
const customEvent = new CustomEvent("customEvent", {
detail: { key: "value" },
});
const targetElement = document.getElementById("myElement");
dispatchEvent(targetElement, customEvent);
```
#### storage module
##### 1. `setStorage(key: string, val: any): void`
Store values to local storage.
- `key` : specifies the name of the key.
- `val` : The value to be stored.
```javascript
const userData = { username: "john_doe", email: "john@example.com" };
setStorage("user_data", userData);
```
##### 2. `getStorage(key: string): any`
Gets the value from local storage.
- `key` : specifies the key name to be obtained.
```javascript
const storedUserData = getStorage("user_data");
console.log(storedUserData);
// Output: {username: 'john_doe', email: 'john@example.com'}
```
##### 3. `clearStorage(key? : string): void`
Clear the value from the local store.
- `key` : specifies the name of the key to be cleared. If no key name is provided, all storage is cleared.
```javascript
clearStorage("user_data"); // Clear the stored value for a specific key name
// or
clearStorage(); // Clear all locally stored values
```
#### log module
##### 1. `logOneLine(str: string, overwrite: boolean = false, wrap: boolean = true): void`
Output logs in one line.
- `str` : The string to be output.
- `overwrite` : Whether to overwrite the current line. The default is' false '.
- `wrap` : Whether to wrap lines after output, defaults to 'true'.
```javascript
logOneLine("This is a single line log message.");
```
##### 2. `logLoop(opts? : { loopList? : string[], isStop? : boolean, timer? : number, index? : number }): { loopList? : string[], isStop? : boolean, timer? : number, index? : number }`
Output a loop animation in the console.
- `opts` : an optional parameter object containing the following properties:
- `loopList` : animation character list, the default is `[' \ \ ', '|', '/', '-', '-']`.
- `isStop` : Whether to stop the loop. The default is' false '.
- `timer` : Animation switch interval (milliseconds), default is' 100 '.
- `index` : indicates the index of the current animated character. The default value is 0.
```javascript
logLoop(); // Start the default loop animation
// or
logLoop({ loopList: ["-", "+", "-", "+"], timer: 200 }); // Start a custom loop animation
```
#### animation module
##### 1. `class AnimateFrame`
A class that provides frame animation.
- `start(duration? : number): void ': Starts frame animation, optional parameter' duration 'is frame number control.
- `stop(): void` : stops frame animation.
```javascript
const animateFrame = new AnimateFrame((timestamp) => {
// Update animation status here
console.log("AnimationFrame callback:", timestamp);
});
animateFrame.start(60); // Start frame animation at 60 frames per second
// Other operations...
animateFrame.stop(); // Stop frame animation
```
##### 2. `quadraticBezier(_x: number, _y: number, t: number): [number, number]`
Calculate the coordinates of points on the quadratic Bessel curve.
- `\_x` : x coordinates of control point 1.
- `\_y` : y coordinate of control point 1.
- `t` : indicates the time parameter. The value ranges from 0 to 1.
```javascript
const result = quadraticBezier(0, 0, 1, 1, 0.5);
console.log(result);
// Output: [0.75, 0.75]
```
##### 3. `cubicBezier(_x1: number, _y1: number, _x2: number, _y2: number, t: number): [number, number]`
Calculate the coordinates of points on a cubic Bezier curve.
- `\_x1` : x coordinate of control point 1.
- `\_y1` : y coordinate of control point 1.
- `\_x2` : control point 2 x coordinates.
- `\_y2` : y coordinate of control point 2.
- `t` : indicates the time parameter. The value ranges from 0 to 1.
```javascript
const result = cubicBezier(0, 0, 0.5, 1, 0.5);
console.log(result);
// Output: [0.375, 0.625]
```
##### 4. `factorial(n: number): number`
Calculate the factorial.
- n: indicates a non-negative integer.
```javascript
const result = factorial(5);
console.log(result);
// Output: 120
```
##### 5. `combination(n: number, k: number): number`
Calculate the number of combinations.
- n: indicates the total number.
- `k` : indicates the number of selected items.
```javascript
const result = combination(5, 2);
console.log(result);
// Output: 10
```
##### 6. `NBezier(points: number[][], t: number): [number, number]`
Calculate the point coordinates on the NTH Bezier curve.
- `points` : array of control points. Each point is a second-order array.
- `t` : indicates the time parameter. The value ranges from 0 to 1.
```javascript
const points = [
[0, 0],
[1, 1],
[2, 0],
];
const result = NBezier(points, 0.5);
console.log(result);
// Output: [1.5, 0.75]
```
#### event-message-center
https://gitee.com/DieHunter/message-center
#### task-queue-lib
https://gitee.com/DieHunter/task-queue
#### js-request-lib
https://gitee.com/DieHunter/js-request-lib
#### js-log-lib
https://gitee.com/DieHunter/js-log-lib