同步操作将从 阿宇的编程之旅/utils-lib-js 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
JavaScript utility functions, packaging some commonly used js functions
npm install utils-lib-js
or
yarn add utils-lib-js
or
pnpm install utils-lib-js
import { defer, messageCenter, TaskQueue, Request } from "utils-lib-js";
const { defer, messageCenter, TaskQueue } = require("utils-lib-js");
<script src="./node_modules/utils-lib-js/dist/umd/index.js"></script>
<script>
console.log(UtilsLib);
</script>
With reference to https://gitee.com/DieHunter/utils-lib-js/blob/master/src/types.ts
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.const randomNumber = randomNum(1, 10);
console.log(randomNumber); // Generates a random integer between 1 and 10
urlSplit(url: string): object
Parses URL query parameters into objects.
url
: indicates the URL containing the query parameter.const url = "https://example.com/path?param1=value1¶m2=value2";
const params = urlSplit(url);
console.log(params);
// Output: {param1: 'value1', param2: 'value2'}
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.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
getType(data: any): string
Get the type of data.
data
: indicates the data to be checked.const dataType = getType("Hello, World!");
console.log(dataType); // Output: string
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.const data = 42;
const allowedTypes = ["number", "string"];
const isTypeAllowed = getTypeByList(data, allowedTypes);
console.log(isTypeAllowed); // Output: true
toKebabCase(camelCase: string, separator: string = "-"): string
The hump name is converted to a hyphenated name
camelCase
: hump type variableseparator
: indicates the separatorconst camelCase = "fontSize";
const kebabCase = toKebabCase(camelCase);
console.log(kebabCase); // Output: font-size
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.const obj = { a: { b: { c: 42 } } };
const value = getValue(obj, "a.b.c", "default");
console.log(value); // Output: 42
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.const obj = { a: { b: { c: 42 } } };
setValue(obj, "a.b.d", "new value");
console.log(obj); // Output: {a: {b: {c: 42, d: 'new value'}}}
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 '.const target = { a: 1 };
const source = { b: 2 };
const result = mixIn(target, source);
console.log(result); // Output: {a: 1, b: 2}
enumInversion(target: object): object
Inverts the key-value pair of an enumeration object.
target
: enumeration object to be reversed.const enumObj = { key1: "value1", key2: "value2" };
const invertedEnum = enumInversion(enumObj);
console.log(invertedEnum); // Output: {value1: 'key1', value2: 'key2'}
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.const result = isNotObject(42, "number");
console.log(result); // Output: false
cloneDeep(target: any): any
Deep clone object.
target
: indicates the object to be cloned.const obj = { a: { b: { c: 42 } } };
const clonedObj = cloneDeep(obj);
console.log(clonedObj); // Output: {a: {b: {c: 42}}}
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.const array = createObjectVariable("array", [1, 2, 3]);
console.log(array); // Output: [1, 2, 3]
createObject(source: object): object
Create objects using a prototype chain.
source
: prototype object.const protoObj = { a: 1 };
const newObj = createObject(protoObj);
console.log(newObj.a); // Output: 1
inherit(source: object, target: function): function
Inherit the prototype chain.
source
: prototype chain of the parent object.target
: constructor of the child object.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
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.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
classDecorator(params: object): ClassDecorator
Add a decorator to the class.
params
: properties and methods to add.@classDecorator({
additionalMethod: function () {
console.log("Additional method");
},
})
class DecoratedClass {}
const instance = new DecoratedClass();
instance.additionalMethod(); // Output: Additional method
stringToJson(target: string): object | null
Converts a JSON string to an object.
target
: JSON string to be converted.const jsonString = '{"key": "value"}';
const jsonObject = stringToJson(jsonString);
console.log(jsonObject); // Output: {key: 'value'}
jsonToString(target: any): string
Converts the object to a JSON string.
target
: indicates the object to be converted.const obj = { key: "value" };
const jsonString = jsonToString(obj);
console.log(jsonString); // Output: '{"key":"value"}'
isWindow(win: any): boolean
Check whether it is a browser window.
win
: indicates the object to be checked.const isBrowserWindow = isWindow(window);
console.log(isBrowserWindow); // Output: true
emptyObject(init: IObject): object
Creates an object whose prototype is empty.
init
: initializes the object.const o = emptyObject({ name: "hunter" });
const o2 = { name: "hunter" };
console.log(o.__proto__, o2.__proto__); // Output: undefined, [Object: null prototype] {}
isEmptyObject(object: IObject<unknown>): boolean
Determines if the object is empty
object
: the target object.const o = isEmptyObject({ name: "a u" });
const o2 = isEmptyObject({});
console.log(o, o2); // Output: false true
arrayRandom(arr: any[]): any[]
Randomly sort the array.
arr
: array to sort.const originalArray = [1, 2, 3, 4, 5];
const randomizedArray = arrayRandom(originalArray);
console.log(randomizedArray);
// Output: a randomly sorted array
arrayUniq(arr: any[]): any[]
Removes duplicate elements from the array.
arr
: array to process.const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = arrayUniq(arrayWithDuplicates);
console.log(uniqueArray);
// Output: Array with duplicate elements removed
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.const nestedArray = [1, [2, [3, [4]], 5]];
const demotedArray = arrayDemote(nestedArray);
console.log(demotedArray);
// Output: reduced array [1, 2, 3, 4, 5]
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).const throttledFunction = throttle(
() => console.log("Throttled function called!"),
1000
);
throttledFunction(); // This command is executed only after 1 second
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).const debouncedFunction = debounce(
() => console.log("Debounced function called!"),
1000
);
debouncedFunction(); // Called multiple times within 1 second, only the last time will be executed
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.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
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.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
requestFrame(callback: (timestamp: number) => void, delay? : number): () => void
Custom frame callbacks for use in browsers and Node.js environments (like setinterval)
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
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.const button = document.getElementById("myButton");
const handleClick = () => console.log("Button clicked! ");
addHandler(button, "click", handleClick);
stopBubble(event: Event): void
Prevent events from bubbling.
event
: indicates an event object.const handleClick = (event) => {
console.log("Button clicked! ");
stopBubble(event);
};
stopDefault(event: Event): void
Default behavior to block events.
event
: indicates an event object.const handleFormSubmit = (event) => {
console.log("Form submitted! ");
stopDefault(event);
};
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.const button = document.getElementById("myButton");
const handleClick = () => console.log("Button clicked! ");
addHandler(button, "click", handleClick);
// Other operations...
removeHandler(button, "click", handleClick);
dispatchEvent(ele: HTMLElement, data: any): void
Trigger a custom event.
ele
: target element.data
: indicates the data of a custom event.const customEvent = new CustomEvent("customEvent", {
detail: { key: "value" },
});
const targetElement = document.getElementById("myElement");
dispatchEvent(targetElement, customEvent);
setStorage(key: string, val: any): void
Store values to local storage.
key
: specifies the name of the key.val
: The value to be stored.const userData = { username: "john_doe", email: "john@example.com" };
setStorage("user_data", userData);
getStorage(key: string): any
Gets the value from local storage.
key
: specifies the key name to be obtained.const storedUserData = getStorage("user_data");
console.log(storedUserData);
// Output: {username: 'john_doe', email: 'john@example.com'}
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.clearStorage("user_data"); // Clear the stored value for a specific key name
// or
clearStorage(); // Clear all locally stored values
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'.logOneLine("This is a single line log message.");
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.logLoop(); // Start the default loop animation
// or
logLoop({ loopList: ["-", "+", "-", "+"], timer: 200 }); // Start a custom loop animation
class AnimateFrame
A class that provides frame animation.
stop(): void
: stops frame animation.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
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.const result = quadraticBezier(0, 0, 1, 1, 0.5);
console.log(result);
// Output: [0.75, 0.75]
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.const result = cubicBezier(0, 0, 0.5, 1, 0.5);
console.log(result);
// Output: [0.375, 0.625]
factorial(n: number): number
Calculate the factorial.
const result = factorial(5);
console.log(result);
// Output: 120
combination(n: number, k: number): number
Calculate the number of combinations.
k
: indicates the number of selected items.const result = combination(5, 2);
console.log(result);
// Output: 10
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.const points = [
[0, 0],
[1, 1],
[2, 0],
];
const result = NBezier(points, 0.5);
console.log(result);
// Output: [1.5, 0.75]
https://gitee.com/DieHunter/message-center
https://gitee.com/DieHunter/task-queue
https://gitee.com/DieHunter/js-request-lib
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。