unselfish
Version:
A high-performance js toolkit
299 lines (220 loc) • 9.1 kB
Markdown
A high-performance js toolkit.Support for use in typescript environment.You can find what you want here ! ! !
It includes lazy loading of data, encapsulation of HTTP requests, detection of common types, acquisition of file MIME types, calculation of the number of characters based on UTF-8 standard, etc.
>
>
> To install
```javascript
npm install unselfish@latest
```
or
```javascript
yarn add unselfish@latest
```
and in your file:
```javascript
import Tools from "unselfish";
/** for Example */
const deb = Tools.debounce();
.
.
.
```
>
>
> To Use
```html
<script type="module">
/** for Example */
import Tools from "unselfish.esm.js";
</script>
```
>
This Api is used for deep copying of Javascript basic types and reference types. Parameter types include Number, String, Object, Array, Symbol, Set, Map, RegExp, Function, Date, Error, etc. You can get a clone Api that is faster than cloneDeep in lodash and more powerful than the native structuredClone Api. This Api has the performance of copying tens of thousands of data in milliseconds. as follows:
- _@param {any} target - Type parameter, you can pass in almost all Javascript type variables._
```javascript
/** for Example */
deepClone(target);
/** Object deep copy */
const o = {name: {k: [1,2,3,4],l: {k: 9}}};
deepClone(o) // {name: {k: [1,2,3,4],l: {k: 9}}}
/** Array deep copy */
const o = [1, 2, 3, 4, {p: {j: {o: 999}}}];
deepClone(o) // [1, 2, 3, 4, {p: {j: {o: 999}}}]
/** Set deep copy */
const o = new Set([1, 2, 3, 4, {p: {j: {o: 999}}}]);
deepClone(o) // Set(5) {1, 2, 3, 4, {p: {j: {o: 999}}}}
/** Map deep copy */
const o = new Map([[1, 3], [3, { n: 888 }]]),
deepClone(o) // Map(2) ([[1, 3], [3, { n: 888 }]])
/** More complex type copy !!!*/
/** Such complex objects can also be copied deeply, and the speed is extremely fast!!! */
let o = {
[]: {
name: 9999
},
"sss": function () {
console.log(121)
},
hh: {
jj: [1, 2, 3, 4, new Date(), new Error("ghhh")]
},
set: new Set([1, 2, 3, 4, new Set(["rr", "ooo", { l: 888 }]), new Map([[1, 3], [3, { n: 888 }]])]),
map: new Map([[1, 3], [3, { n: 888 }], ["ss", new Set([1, 2, 3, 4, new Set(["rr", "ooo", { l: 888 }]), new Map([[1, 3], [3, { n: 888 }]])])]])
}
deepClone(o) // ...
.
.
.
.
.
```
>
This is different from the traditional debounce. Two schemes are used here. One is that the first trigger will be effective, and the other is that the first trigger will not be effective. as follows:
```javascript
const debounce = Tools.debounce();
```
- _@param {Function} function - Argument to function._
- _@param {any[]} param - Execute function body._
- _@param {time} time - delay time._
- _@param {firstEffect} firstEffect(Optional) - Is it effective for the first time. Default is true._
```javascript
debounce(func, param, time, firstEffect);
```
>
The throttling function here is different from the general implementation method, Two schemes are used here. One is that the first trigger will be effective, and the other is that the first trigger will not be effective. as follows:
```javascript
const throttle = Tools.throttle();
```
- _@param {Function} function - Argument to function._
- _@param {any[]} param - Execute function body._
- _@param {time} time - delay time._
- _@param {firstEffect} firstEffect(Optional) - Is it effective for the first time. Default is true._
```javascript
throttle(func, param, time, firstEffect);
```
>
This API is mainly used to calculate the length of strings based on UTF-8 encoding. You can use this to obtain the length of characters encoded by Concorde Unicode. as follows:
- _@param {string} \_data - The length of the string needs to be calculated._
- _@return {number} - Returns the calculated length._
```javascript
const _len = Tools.byteLength(_data);
/** for Example */
Tools.byteLength("china") // 5
Tools.byteLength("中国") // 6
.
.
.
```
>
This API is mainly used to detect the data type of javascript and return the lowercase type name. as follows:
- _@param {any} target - Data to be detected._
- _@return {string} - Lowercase name of return type._
```javascript
const _len = Tools.checkType(_data);
/** for Example */
Tools.checkType("china") // string
Tools.checkType(Symbol("china")) // symbol
Tools.checkType({country: "china"}) // object
Tools.checkType(["china"]) // array
Tools.checkType(undefined) // undefined
Tools.checkType(null) // null
Tools.checkType(NaN) // number
.
.
.
```
>
Get the format of incoming data resources, such as pictures, audio, video, documents, zip, zip, rar, html, etc. be careful: ==The data source here must be in the ArraryBuffer format==. as follows:
- _@param {ArrayBuffer} buffer - Get the MIME type of the data resource._
- _@return {object} - Returns the type of the containing file and the MIME type name._
```javascript
/** for Example */
const _data = new ArrayBuffer(557);
const _type = Tools.getFileMimeType(_data); // {filetype: 'svg', mimetype: 'image/svg+xml'}
.
.
.
```
>
This API is mainly used to load visible resources and realize on-demand loading. For example: pictures, videos, etc. This function is mainly implemented using the IntersectionObserver Api of H5. Performance and compatibility are relatively objective. as follows:
- _@param { {lazyAttr: string,loadType: string} } lazyParams - This parameter passes in the attributes of the display and hidden phases of the resource,For example: lazy and src._
- _@param { {root: Element;rootMargin: string;threshold: number;} } intersectionOptions - Returns the type of the containing file and the MIME type name._
```javascript
/** for Example */
lazyLoading(lazyParams, intersectionOptions);
/** Attributes of the original display, such as a small blank image, or loading.gif. */
const attr = lazyAttr || "lazy";
/** When reaching a certain threshold, you need to replace the original resources with the incoming resources, such as displaying real pictures or videos. */
const type = loadType || "src";
.
.
.
```
>
The API is implemented based on XMLHttpRequest, providing more flexible and rich functions, making up for the lack of schedule control in fetch, and meeting the needs of traditional http developers. as follows:
- _@param {XHRParams} parameter - The incoming parameters are some parameters and data content needed to integrate traditional HTTP requests. They are easier to control and use, and are faster and more flexible than axios._
```javascript
/** for Example */
XHRRequest(parameter);
/** XHRParams Type */
type XHRParams = {
/** The requested base path */
baseUrl: string,
/** Requested file path */
url?: string,
/** Requested method */
method: "GET" | "POST" | "PUT" | "DELETE" | "OPTIONS" | "TRACH" | "HEAD" | "CONNECT",
/** Whether the status code returned by the request is strictly required to be a specific value */
strict?: boolean,
/**
* Parameter transfer object
*
* ### `Json 'parameter is' object'`
*
* const _data = { name: "china"}
*
* ### `FormData when uploading pictures`
*
* const _data = new FormData();
*
* _data.append("img", file); // `Img 'is the' key 'field agreed with the background
*
* ### Use common form to transfer parameters
*
* const _data = "name=tong&id=1999";
*
*/
data: object | string | FormData,
/** Timeout milliseconds */
overtime?: number,
/** `XMLHttpRequest. header ` Set object */
headers?: { [key: string]: string }
/**
* Interface data response type
* - Default ` json`
*/
responseType: XMLHttpRequestResponseType,
/** Whether the result of the response is serialized */
serialization?: boolean,
/** Successful callback */
success?(
/** Response result */
res: any,
/** Response to original data result */
response: XMLHttpRequest
): void,
/** Failed callback */
fail?(value: XMLHttpRequest): void,
/** Timeout callback */
timeout?(value: XMLHttpRequest): void,
/** Request progress callback */
progress?(event: ProgressEvent<XMLHttpRequestEventTarget>): void
};
.
.
.
```