npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

xstao-common-util-global

v1.0.3

Published

前后端通用的工具库

Downloads

17

Readme

xstao-common-util-global

xstao-common-util-global是一个前后通用的工具库,包含一些js通用的方法

安装方法

npm install xstao-common-util-global --save

工具

CustomArray-自定义数组

  • API

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
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

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

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

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

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

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
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

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
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

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
const {regexConst} = require("xstao-common-util-global")
console.log(regexConst.DAY.test("2019-01-01"))          //输出:true