# xstao-common-util-global

> 前后端通用的工具库

Latest version **1.0.3** (published 2022-01-01) · ISC license · 0 weekly downloads

## Install

```sh
npm install xstao-common-util-global
pnpm add xstao-common-util-global
yarn add xstao-common-util-global
bun add xstao-common-util-global
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.3 |
| Published | 2022-01-01 |
| First published | 2021-12-31 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 2 |
| Unpacked size | 93.3 KB |
| Known vulnerabilities | 0 (+25 in 1 direct dependencies) |
| Install scripts | no |
| Author | xstao |
| Maintainers | xstao |

## Links

- npm: https://www.npmjs.com/package/xstao-common-util-global
- npm.io page: https://npm.io/package/xstao-common-util-global

## Dependencies (2)

- [axios](https://npm.io/package/axios.md) ^0.19.2
- [crypto-js](https://npm.io/package/crypto-js.md) ^4.0.0

## Recent versions

- 1.0.3 (latest) — 2022-01-01
- 1.0.1 — 2021-12-31
- 1.0.0 — 2021-12-31

## README

# xstao-common-util-global 

xstao-common-util-global是一个前后通用的工具库,包含一些js通用的方法

## 安装方法
npm install xstao-common-util-global --save

+ [工具](#工具)
    + [CustomArray-自定义数组](#CustomArray-自定义数组)
    + [CustomDate-自定义日期](#CustomDate-自定义日期)
    + [CustomJson-自定义json](#CustomJson-自定义json)
    + [CustomString-自定义字符串](#CustomString-自定义字符串)
    + [http-http请求](#http-http请求)
    + [regexConst-常用的正则表达式常量](#regexConst-常用的正则表达式常量)

## 工具

### CustomArray-自定义数组

+ API

```ts

declare class CustomArray {
    public value: Array<any>

    constructor(value: Array<any>)

    // 聚合
    aggregate(json: {
        // 聚合的主键
        key: Array<string>
        // 需要聚合的值(未声明的会被忽略)
        value: Array<{ id: string; type: string }>
    }): CustomArray

    // 转为嵌套数组
    toNestArray(
        // 子数组元素的个数
        num: Number
    ): Array<any>

    // 按key比较两个数组对象的不同
    static getTwoArrayDiffChange<RowInterface>(jsonParam: {
        // 旧数组
        oldArray: Array<RowInterface>
        // 新数组
        newArray: Array<RowInterface>
        // 比较的key
        keys: Array<string>
    }): {
        // 新增项
        addArray: Array<RowInterface>
        // 删除项
        deleteArray: Array<RowInterface>
        // 修改项
        alterArray: Array<{
            // key对应的json
            keyJson: {
                [propName: string]: any
            }
            // 排除key后的旧json值
            oldValueJson: {
                [propName: string]: any
            }
            // 排除key后的新json值
            newValueJson: {
                [propName: string]: any
            }
        }>
    }
}

```

+ Demo

```js
const {CustomArray} = require("xstao-common-util-global")

//聚合
let arr1 = new CustomArray([{a:1,b:2,c:3,d:4,e:100,f:200},{a:1,b:5,c:6,d:8,e:500,f:600}])
arr1 = arr1.aggregate({
    key:["a"],
    value:[
        {id:"b",type:"sum"},
        {id:"c",type:"count"},
        {id:"d",type:"avg"},
        {id:"e",type:"max"},
        {id:"f",type:"min"},
    ]
})
console.log(arr1.value)         //输出:[{a:1,b:7,c:2,d:6,e:500,f:200}]

//转为嵌套数组
let arr2 = new CustomArray([1,2,3,4,5])
arr2 = arr2.toNestArray(2)
console.log(arr2)         //输出:[[1,2],[3,4],[5]]
```

### CustomDate-自定义日期

+ API

```ts

declare class CustomDate {
    public value: Date

    // 构造方法参数未定义时,使用当前时间;string类型支持yyyy-MM-dd hh:mm:ss和yyyy-MM-dd两种格式
    constructor(value?: string | Date)

    // 增加偏移
    add(jsonParam: {
        // 年
        year?: number
        // 月
        month?: number
        // 日
        day?: number
        // 时
        hour?: number
        // 分
        minute?: number
        // 秒
        second?: number
    }): CustomDate

    // 转为当前日期对应的星期一
    toMonday(): CustomDate

    // 转为当前日期对应的星期天(星期天按一周的最后一天计算)
    toSunday(): CustomDate

    // 转为日期字符串,即yyyy-MM-dd
    toDateStr(): string

    // 转为时间字符串,即yyyy-MM-dd hh:mm:ss
    toDateTimeStr(): string

    // 是否为闰年
    isLeapYear(): boolean

    // 获取当然日期所在月的天数
    getDaysOfMonth(): number
}

```

+ Demo

```js

const {CustomDate} = require("xstao-common-util-global")

let date1 = new CustomDate("2019-07-02 00:00:00")

//日期加减
console.log(date1.add({year:1}).toDateTimeStr())    //输出:2020-07-02 00:00:00

//转为当周的星期一
console.log(date1.toMonday().toDateTimeStr())       //输出:2020-07-01 00:00:00

//转为当周的星期天
console.log(date1.toSunday().toDateTimeStr())       //输出:2020-07-07 00:00:00

//转为mysql的date格式的字符串
console.log(date1.toDateStr())                      //输出:2020-07-02

//转为mysql的datetime格式的字符串
console.log(date1.toDateTimeStr())                  //输出:2020-07-02 00:00:00

//判断是否为闰年
console.log(date1.isLeapYear())                     //输出:false    

//获取当月的天数
console.log(date1.getDaysOfMonth())                 //输出:31

```

### CustomJson-自定义json

+ API

```ts

declare class CustomJson {
    constructor(value: { [propName: string]: any })

    // 根据key将对象划分为key和value
    getKeyValueByKeys(
        // 主键
        keys: Array<string>
    ): {
        // key组成的json
        keyJson: { [propName: string]: any }
        // 值组成的json
        valueJson: { [propName: string]: any }
    }
}

```

+ Demo

```js

const {CustomJson} = require("xstao-common-util-global")

const j = new CustomJson({ a: 1, b: 2, c: 3, d: 4 })
const r = j.getKeyValueByKeys(['a', 'b'])

console.log(JSON.stringify(r)) // 输出 {"keyJson":{"a":1,"b":2},"valueJson":{"c":3,"d":4}}

```

### CustomString-自定义字符串

+ Api

```ts

declare class CustomString {
    public value: string

    constructor(value?: string)

    // utf8编码
    utf8Encode(): CustomString

    // utf8解码
    utf8Decode(): CustomString

    // url编码
    urlEncode(): CustomString

    // url解码
    urlDecode(): CustomString

    // md5签名(32位小写)
    md5With32LowerCase(): CustomString

    // mysql插入前转义
    toSqlEscape(): string

    // 生成随机数
    static buildRandomStr(jsonParam: {
        // 字符串池子
        strPool: string
        // 随机数长度
        length: number
    }): string
}

```

+ Demo

```js
const {CustomString} = require("xstao-common-util-global")

//utf8编码
let str1 = new CustomString("方式")
console.log(str1.utf8Encode())                      //输出:&#x65B9;&#x5F0F;

//utf8解码
let str2 = new CustomString("&#x4F5B;&#x5C71;&#x5E02;")
console.log(str2.utf8Decode())                      //输出:佛山市

//url编码
let str3 = new CustomString("发生大幅")
console.log(str3.urlEncode())                       //输出:%e5%8f%91%e7%94%9f%e5%a4%a7%e5%b9%85

//url解码
let str4 = new CustomString("%e9%a3%9e%e6%b4%92%e5%8f%91%e7%94%9f%e9%a3%9e%e6%b4%92%e5%8f%91")
console.log(str4.urlDecode())                       //输出:飞洒发生飞洒发

//md5签名(32位小写)
let str7 = new CustomString("妈咪妈咪妈咪妈咪们")
console.log(str7.md5With32LowerCase())               //输出:62cca390106404ebc3466f86da9bc99f

//mysql插入前转义
let str8 = new CustomString("'")
console.log(str8.toSqlEscape())                      //输出:\\'

//生成随机数
let str9 = CustomString.buildRandomStr({strPool:'123abc',length:3})
console.log(str9)                                    //输出示例:a31

```

### http-http请求

+ API

```ts

export interface HttpJsonParam extends AxiosRequestConfig {
    // jwt令牌存储在LocalStorage中的主键名称
    jwtLocalStorageName?: string
    // jwt令牌存储在SessionStorage中的主键名称
    jwtSessionStorageName?: string
    // 重试次数
    times?: number
    // 是否为公司http返回值规范,参考 http://aiki.avalongames.com:8090/pages/viewpage.action?pageId=8159346
    isAvalonResponse?: boolean
}

export interface HttpResponse {
    // http状态码
    httpStatusCode: number
    // 业务状态码
    status: number
    // 业务数据
    data: any
    // 链接信息
    _links: object
}

declare module http {
    // get请求
    function doGet(
        // http请求参数
        jsonParam: HttpJsonParam
    ): Promise<HttpResponse | any>

    // post请求
    function doPost(
        // http请求参数
        jsonParam: HttpJsonParam
    ): Promise<HttpResponse | any>

    // put请求
    function doPut(
        // http请求参数
        jsonParam: HttpJsonParam
    ): Promise<HttpResponse | any>

    // patch请求
    function doPatch(
        // http请求参数
        jsonParam: HttpJsonParam
    ): Promise<HttpResponse | any>

    // delete请求
    function doDelete(
        // http请求参数
        jsonParam: HttpJsonParam
    ): Promise<HttpResponse | any>
}

```

+ Demo

```js
const {http} = require("xstao-common-util-global")

const axios = require('axios')

const { CancelToken } = axios
let cancel

const test = async url => {
    try {
        const r = await http.doGet({
            url,
            // 取消参数
            cancelToken: new CancelToken(function executor(c) {
                cancel = c
            }),
        })
        console.log(r)
    } catch (e) {
        console.log(e)
    }
}

test(xxxxx)

setTimeout(() => {
    // 取消http请求
    cancel('Operation canceled by the user.')
}, 500)

```

### regexConst-常用的正则表达式常量

+ API

```ts

declare module regexConst {
    // 日期精确到日,即yyyy-MM-dd
    const DAY: RegExp
    // 日期精确到秒,即yyyy-MM-dd hh:mm:ss
    const SECOND: RegExp
    // 日期精确到日或秒,即yyyy-MM-dd或yyyy-MM-dd hh:mm:ss
    const DAY_OR_SECOND: RegExp
    // 整数,支持负数
    const INT: RegExp
    // 数字,支持负数和小数
    const NUMBER: RegExp
    // 日期精确到月,即yyyy-MM
    const MONTH: RegExp
}

```

+ Demo

```js
const {regexConst} = require("xstao-common-util-global")
console.log(regexConst.DAY.test("2019-01-01"))          //输出:true
```

---
_Source: https://npm.io/package/xstao-common-util-global · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
