2.0.21 • Published 2 months ago
@qingbing/ts-utils v2.0.21
version
- 2.0.18
- lib/collection
- static values(kvs: TObject, keys: PropertyKey[]): TObject, 查找所有匹配的对象, 并构建新的对象
- lib/collection
- 2.0.18
- lib/formatter
- date: 日期格式化函数, 指定格式: (Yy: 年; Mm: 月; Dd: 日; Hh: 时; Ii: 分; Ss: 秒; Aa: 毫秒)
- ~ replace 方法添加 leftSymbol 和 rightSymbol 参数, 兼容老版本,不影响之前代码
- lib/formatter
- 2.0.16
- type/index
- TObject: 可列表的对象类型
- type/index
- 2.0.15
- 去除 storage 解码日志
- 2.0.14
- 修正类型的导入为
import type
- 修正类型的导入为
- 2.0.13
- storage
- 修改 index.d.ts 原型和定义保持一致
- storage
- 2.0.12
- convert
- class ConvertDate
static date2Timestamp(date?: Date): number
: 日期数据转换成时间戳 毫秒
static timestamp2Date(timestamp?: number)
: 毫秒转换成日期数据
- convert
- 2.0.11
- assistant
CopyToClipboard(text: string, opts?: CopyClipboardOptions): boolean
: 将字符串拷贝到剪贴板中, 需要使用到 window
- assistant
- 2.0.10
- download
static instance(charset?: string): Download
: 获取下载实例setCharset(charset: string): Download
: 设置下载文件字符集setBlobText(text: unknown): Download
: 设置下载的 blob 内容setExtension(extension: string | null): Download
: 设置下载文件后缀setFilename(filename: string): Download
: 设置下载文件名generateFilename(): Download
: 手动创建文件名download(): void
: 下载文件
- basic
- +
isSymbol(v: unknown): v is symbol
: 判断一个变量是否是 symbol
- +
- 2.0.9
- basic
toJson(v: unknown): any | null
->toJson(v: unknown): any | null
: 将变量(json字符串)转换成json对象
- basic
- 2.0.8
- +color
static random(withAlpha?: boolean): string
: 随机获取 rgb 或 rgba 颜色值
- +color
- 2.0.7
- base
getRandomInt()
: 获取范围内的随机数
- type/index
- +
export interface IRemoteResult<T>
- +
export interface IRemotePagingData<T>
- +
export interface IRemotePagingResult<T>
- +
- base
- 2.0.6
- type/index
TRecord = Record<string, any>
: 修改了表达方式
- formatter
- class Formatter
static replace(msg: string, kvs: TRecord): string
: 字符串对象替换
- class Formatter
- convert
- class ConvertDataType
static AtoO<T>(a: T[]): TRecord
: array 转变为 key-value 形式的 record
- class ConvertDataType
- type/index
- 2.0.4
- type
Writable<T> = {-readonly [P in keyof T]: T[P]}
: 取消所有属性的 readonly
- type
- 2.0.3
- assistant
- +
mixins(setting: any, ...objs: unknown[]): any
: array 或 object 的混入
- +
- assistant
- 2.0.2
- basic
isDev(): boolean
: 判断当前环境是否是 development 环境- ~
isString(v: unknown): v is string
: 判断一个变量是否是 string 类型 - ~
isUndefined(v: unknown): v is undefined
: 判断一个变量是否是 undefined 类型 - ~
isBoolean(v: unknown): v is boolean
: 判断一个变量是否是bool类型 - ~
isNumber(v: unknown): v is number
: 判断一个变量是否是数字类型 - ~
isArray(v: unknown): v is Array<unknown>
: 判断一个变量是否是数组 - ~
isObject(v: unknown): v is Record<any, any>
: 判断一个变量是否是Object - ~
isFunction(v: unknown): v is Function
: 判断一个变量是否是函数 - +
isSymbol(v: unknown): v is symbol
: 判断一个变量是否是 symbol - +
isPromise<T = any>(v: unknown): v is Promise<T>
: 判断一个变量是否是 promise 对象 - +
isPlainObject(v: unknown): v is object
: 断一个变量是否是 {} 对象 isEmpty(v: any): boolean
: 判断一个变量是否为空uniqid(): string
: 生成唯一的UUID
- basic
- 2.0.1
- assistant
- class Dump
static error(msg: TMessage): void
: 打印错误信息static log(message?: any, ...optionalParams: any[]): void
: 打印消息static info(message?: any, ...optionalParams: any[]): void
: 打印提示消息static warn(message?: any, ...optionalParams: any[]): void
: 打印警告信息
- class Dump
- prototype
Array.prototype.remove = function <T>(o: T): T[]
: 从数组中移除元素Array.prototype.has = function <T>(o: T): boolean
: 判断数组中是否拥有元素
- crypt
- class Json
static encode(str: any): string
: json 编码static decode(data: string): any
: json 解码
- class Base64
static encode(str: any, urlSafe?: boolean): string
: base64 编码static encodeURI(str: any): string
: base64 URI 编码static encodeURL(str: any): string
: base64 URL 编码static decode(data: string): any
: base64 解码
- class Json
- formatter
- class Formatter
static sprintf(...params: any): string
: 字符串占位替换
- class Formatter
- convert
- class ConvertDataType
static StoI(s: string): number
: string 转变为 numberstatic ItoS(i: number): string
: number 转变为 stringstatic OtoA<T extends object>(obj: T): T[Extract<keyof T, string>][]
: object 转换成 array
- class ConvertDataType
- storage
- Local
static get<T>(key: TKey): IStorageResult<T | null>
: 获取 localStorage 信息static set<T>(key: TKey, value: T, expire?: TExpire): void
: 保存 localStorage 信息, 可以设置保存时间(毫秒)static setAt<T>(key: TKey, value: T, expire?: TExpire): void
: 保存 localStorage 信息,同时设置有效期(时间戳)static remove(key: TKey): void
: 删除 localStorage 信息static clear(): void
: 清空 localStorage 信息
- Session
static get<T>(key: TKey): IStorageResult<T | null>
: 获取 sessionStorage 信息static set<T>(key: TKey, value: T): void
: 保存 sessionStorage 信息static remove(key: TKey): void
: 删除 sessionStorage 信息static clear(): void
: 清空 sessionStorage 信息
- Cookie
static get(key: TKey): any
: 获取 document.cookie 信息static set<T>(key: TKey, value: T, duration?: number | undefined, setting?: Partial<CookieAttributes>): void
: 保存 document.cookie 信息, 可以设置有效时间(毫秒)static setAt<T>(key: TKey, value: T, expire?: Date | undefined, setting?: Partial<CookieAttributes>): void
: 保存 document.cookie 信息,同时设置有效期(日期)static remove(key: TKey): void
: 删除 document.cookie 信息static clear(): void
: 清空 document.cookie 信息
- Local
- collection
- class Col
static each<K, V, T extends IEach<K, V> | object>(kvs: T, callbackfn: (value: V | T[Extract<keyof T, string>], key: K | Extract<keyof T, string>, all: T) => boolean | void): void
: 遍历集合, 主要用于 object, array, set, mapstatic value<K, V, T extends IEach<K, V> | object>(kvs: T, key: K, defaultVal?: V | null): V | null
: 查找集合中字段的值static column(items: TRecord[], keyName: any, valueName: any, defaultVal?: any): TRecord
: 从二维表中挑选两列,一列作为 key , 一列作为 value, 组成一个 IRecord
- class Col
- string
explode(val: string | string[], delimiter: string): string[]
: 将变量分割成数组
- process
- class ProcessAlone
static instance(): ProcessAlone
: 创建事件独占实例start(cb: TCallableVoid)
: 事件开始执行函数isRunning(): boolean
: 是否正在执行over(cb?: TCallableVoid)
: 事件结束必须执行
- class Idempotent
static instance(): Idempotent
: 创建幂等实例setRunningMsg(msg: string)
: 设置幂等处理消息run(uk: TKey, callback: (cb: TCallableVoid) => void, obj?: any)
: 执行幂等逻辑
- class ProcessAlone
- promise
PromiseAll<T extends object>(promises: T): Promise<T>
: 异步获取远程数据
- type
TCallableVoid = () => void
: 定义返回空的回调函数类型TMessage = string
: 定义字符消息类型TKey = string
: 字符 key 的类TExpire = Dict.permanent | number
: 时间有效期类型: Dict.permanent 表
- assistant
1. 在 node 中安装使用
npm install @qingbing/ts-utils
2. 通用 type 类型
/**
* Make all properties in T writable
*/
export type Writable<T> = {
-readonly [P in keyof T]: T[P];
};
// 定义返回空的回调函数类型
export type TCallableVoid = () => void;
// 定义参数为一个字符串,返回为空的回调函数类型
export type TStringCallableVoid = (v: string) => void;
// 定义字符消息类型
export type TMessage = string;
// 字符 key 的类型
export type TKey = string;
// db-record
export type TRecord = Record<string, any>;
// 可列的对象类型
export type TObject = Record<PropertyKey, any>;
// 时间有效期类型: Dict.permanent 表示永久; number 用于表示时间戳
export type TExpire = Dict.permanent | number;
/**
* 后段数据相应接口接口
*/
// 后段整体数据结构
export interface IRemoteResult<T> {
msg?: string
code: number | string
data?: T
}
// 分页数据结构
export interface IRemotePagingData<T> {
pageSize?: number
pageNo?: number
totalCount?: number
data: T[]
}
// 后段整体分页数据结构
export interface IRemotePagingResult<T> extends Omit<IRemoteResult<T>, 'data'> {
data: IRemotePagingData<T>
}
- test
const result: IRemoteResult<null> = {
msg: "ok",
code: 0,
}
console.log(result);
const pageData: IRemotePagingData<{ id: number, name: string }> = {
pageNo: 1,
pageSize: 10,
data: [
{
id: 1,
name: "qing"
},
{
id: 1,
name: "bing"
},
]
}
console.log(pageData);
const pageResult: IRemotePagingResult<{ id: number, name: string }> = {
msg: "ok",
code: 1,
data: {
pageNo: 1,
pageSize: 1,
totalCount: 1,
data: [
{
id: 1,
name: "qing"
},
{
id: 1,
name: "bing"
},
]
}
}
console.log(pageResult);
3. 使用示例
3.1 使用 prototype
import './index'
console.log([1, 2, 4, 5].remove(4));
console.log([1, 2, 4, 5].remove(0));
console.log([1, 2, 4, 5].has(4));
console.log([1, 2, 4, 5].has(0));
3.2 使用 basic 函数
import { isArray, isBoolean, isDev, isEmpty, isFunction, isNumber, isObject, isPlainObject, isPromise, isString, isSymbol, isNull, isUndefined, toJson, uniqid } from './index'
console.log('isDev', isDev());
console.log('isUndefined', isUndefined(undefined)); // true
console.log('isString', isString("12")); // true
console.log('isString', isString(12)); // false
console.log('isBoolean', isBoolean(true)); // true
console.log('isBoolean', isBoolean("true")); // false
console.log('isNumber', isNumber(12.2)); // true
console.log('isNumber', isNumber('12.2')); // false
console.log('isArray', isArray([])); // true
console.log('isObject', isObject({})); // true
console.log('isObject', isObject([])); // true
console.log('isObject', isObject(Promise.resolve())); // true
console.log('isObject', isObject(() => { })); // false
console.log('isFunction', isFunction(() => { })); // true
console.log('isFunction', isFunction({})); // false
// isEmpty
console.log('isEmpty', isEmpty(undefined)); // true
console.log('isEmpty', isEmpty(null)); // true
console.log('isEmpty', isEmpty('')); // true
console.log('isEmpty', isEmpty([])); // true
console.log('isEmpty', isEmpty({})); // true
// uniqid
console.log('uniqid', uniqid());
// toJson
console.log('toJson', toJson("{\"name\":\"qingbing\"}")); // { name: 'qingbing' }
console.log('toJson', toJson("name")); // name
console.log('toJson', toJson(11)); // 11
console.log('toJson', toJson("11")); // 11
console.log('toJson', toJson("true")); // true
console.log('toJson', toJson(true)); // true
console.log('toJson', toJson({ name: "qing" })); // { name: "qing" }
console.log('toJson', toJson([11, "bing"])); // [11, "bing"]
// isSymbol
console.log('Symbol', isSymbol(Symbol(11))); // true
console.log('Symbol', isSymbol(Symbol("11"))); // true
console.log('Symbol', isSymbol(11)); // false
// isNull
console.log('isNull', isNull(null)); // true
console.log('isNull', isNull(undefined)); // false
console.log('isNull', isNull(1)); // false
// isPromise
console.log('isPromise', isPromise(new Promise(resolve => { }))); // true
console.log('isPromise', isPromise(Promise.resolve())); // true
// console.log('isPromise', isPromise(Promise.reject())); // true, 需要 catch, 否则报错
// isPlainObject
console.log('isPlainObject', isPlainObject({})); // true
console.log('isPlainObject', isPlainObject([])); // false
3.3 使用 string 函数
import { explode } from './index'
console.log('explode', explode("i am qq", " "));
console.log('explode', explode("i am qq", "am"));
console.log('explode', explode(["i am qq"], "am"));
3.4 使用 assistant 函数
import { Dump, mixins, CopyToClipboard } from "./index";
const aa1 = [
{
path: "/login",
meta: { title: "登录" },
},
{
path: "/",
meta: {
title: "控制面板",
realPath: "/dashboard",
},
children: [
{
path: "",
redirect: "dashboard",
},
],
},
]
const aa2 = [
{
path: "/personal",
meta: {
title: "个人中心",
realPath: "/personal/index",
},
children: [
{
path: "",
redirect: "index",
},
{
path: "index",
meta: { title: "个人信息" },
},
],
},
]
const aa3 = [
{
path: "/logs",
meta: {
title: "日志管理",
realPath: "/logs/operate",
},
children: [
{
path: "",
redirect: "operate",
},
{
path: "operate",
meta: { title: "操作提示日志" },
},
],
},
];
const oo1 = {
path: "/logs",
meta: {
title: "日志管理",
realPath: "/logs/operate",
},
children: [
1, 2
]
}
const oo2 = {
path1: "/logs",
meta: {
title1: "日志管理",
realPath1: "/logs/operate",
},
children: [
1, 3, 4
]
}
const oo3 = {
path1: "/logs",
meta: {
title1: "日志管理",
realPath1: "/logs/operate",
},
name: "test",
children: [
1, 3, 4
],
call: () => {
console.log('call');
}
}
const xx1 = mixins(aa1, aa2, aa3)
console.log(xx1);
const xx = mixins(oo1, oo2, oo3)
console.log(xx);
Dump.log('log message', [12], { name: "bing" });
Dump.info('info message', [12], { name: "bing" });
Dump.warn('warn message', [12], { name: "bing" });
Dump.error('Error message');
CopyToClipboard("text message")
3.5 使用 crypt 函数
import { Base64, Json } from './index'
let encodeStr: string;
encodeStr = Json.encode("good");
console.log(encodeStr);
console.log(Json.decode(encodeStr));
encodeStr = Json.encode({ name: "bing" });
console.log(encodeStr);
console.log(Json.decode(encodeStr));
encodeStr = Base64.encode("http://qiyezhu.net/index.html?name=qing&sex=nan");
console.log(encodeStr);
console.log(Base64.decode(encodeStr));
encodeStr = Base64.encode("http://qiyezhu.net/index.html?name=qing&sex=nan", true);
console.log(encodeStr);
console.log(Base64.decode(encodeStr));
encodeStr = Base64.encodeURI("http://qiyezhu.net/index.html?name=qing&sex=nan");
console.log(encodeStr);
console.log(Base64.decode(encodeStr));
encodeStr = Base64.encodeURL("http://qiyezhu.net/index.html?name=qing&sex=nan");
console.log(encodeStr);
console.log(Base64.decode(encodeStr));
3.6 使用 formatter 函数
import { Formatter } from './index'
console.log(Formatter.sprintf("我是 %s, 今年 %d 岁,基础信息: %j", "张三", 5, { "age": 44, "high": 1.12 }));
console.log(Formatter.replace("我是 {name}, 今年 {age} 岁,基础信息: {info}", {
name: "张三",
age: 12,
info: { "age": 44, "high": 1.122, haha: true }
}));
console.log(Formatter.date()); // 当前时间, 默认格式
console.log(Formatter.date(undefined, "Y-M-D")); // 当前时间, 指定格式
console.log(Formatter.date(undefined, "Y-M-D H:I:S.Az")); // 当前时间, 携带毫秒
console.log(Formatter.date(1049494028009)); // 默认时间
console.log(Formatter.date(1049494028009, "Y-M-D")); // 指定格式
console.log(Formatter.date(1049494028009, "Y-M-D H:I:S.Az")); // 携带毫秒
console.log(Formatter.date("2003-04-05 06:07:08.009")); // 默认时间
console.log(Formatter.date("2003-04-05 06:07:08.009", "Y-M-D")); // 指定格式
console.log(Formatter.date("2003-04-05 06:07:08.009", "Y-M-D H:I:S.Az")); // 携带毫秒
3.7 使用 convert 函数
import { ConvertDataType, ConvertDate } from './index'
/**
* convert - type ok
*/
console.log(ConvertDataType.StoI("12"));
console.log(ConvertDataType.ItoS(12));
console.log(ConvertDataType.AtoO(["qing", "bing"]));
console.log(ConvertDataType.OtoA({ "1": "qing", "2": "bing", "4": "qiye" }));
/**
* convert - date ok
*/
const date = ConvertDate.timestamp2Date();
console.log(date);
console.log(ConvertDate.date2Timestamp(date));
3.8 使用 storage 函数
import { Cookie, Local, Session } from './index'
// localStorage
// 设置 localStorage
Local.set("id", "name");
// 获取 localStorage
Local.get("id");
// 移除 localStorage
Local.remove("id");
// 清空 localStorage
Local.clear();
// Session
// 设置 sessionStorage
Session.set("id", "name");
// 获取 sessionStorage
Session.get("id");
// 移除 sessionStorage
Session.remove("id");
// 清空 sessionStorage
Session.clear();
// cookie
Cookie.set("id", "name");
Cookie.set("id", "name", 60 * 15); // 15分钟有效
Cookie.set("id", "name", new Date().setTime(new Date().getTime() + 60 * 15 * 1000)); // 15分钟有效
// 获取 Cookie
Cookie.get("id");
// 移除 Cookie
Cookie.remove("id");
// 清空 Cookie,目前不支持,会控制台提示
// Cookie.clear();
3.9 使用 collection 函数
import { Col } from './index'
// Col.each 测试
Col.each(new Map([["name", "qing"], ["sex", "nan"]]), (value, key): boolean => {
console.log(value, key);
return true;
})
Col.each({ "name": 1 }, (value, key): boolean => {
console.log(value, key);
return true;
})
Col.each([1, 2, 3], (value, key): boolean => {
console.log(value, key);
return true;
})
Col.each(["qing", "bing"], (value, key): boolean => {
console.log(value, key);
return true;
})
Col.each([11, 22, "bing"], (value, key): boolean => {
console.log(value, key);
return true;
})
// Col.value 测试
Col.value<string, string, Map<string, string>>(new Map([["name", "qing"], ["sex", "nan"]]), "name", "xxx")
Col.value({ "name": 1, "sex": "12" }, 1, "xxx")
Col.value<number, number, number[]>([1, 2, 3], 4, 222)
Col.value<number, string, string[]>(["qing", "bing"], 1, "xxx")
Col.value<number, any, any[]>([11, 22, "bing"], 1, "xxx")
// Col.column 测试
const items = [
{
id: 22,
field: "name",
default: "q",
label: "qing",
},
{
id: 33,
field: "sex",
default: "qsss",
label: "bing",
age: 222,
},
];
console.log("===============");
const data = Col.column(items, "id", "label");
console.log(data);
console.log("===============");
3.10 使用 process 函数
import { Alone, Idempotent } from './index'
const aloneInstance = Alone.instance()
aloneInstance.start(() => {
// 逻辑方法写这里
console.log(aloneInstance.isRunning());
setTimeout(() => {
aloneInstance.over();
console.log(aloneInstance.isRunning());
console.log("Alone - over", aloneInstance.isRunning());
}, 1000);
});
Idempotent
.instance()
.setRunningMsg('正在使用')
.run("uniqidKey", (cb) => {
// 逻辑方法写这里
console.log("running");
setTimeout(() => {
cb(); // 关闭幂等标记, 如果不回调,将永远退不出幂等
console.log("Idempotent - over");
}, 1000);
});
3.11 使用 promise 函数
- 同步使用
import { PromiseAll } from './index'
const ps = PromiseAll({
name: new Promise(resolve => {
resolve("bing")
}),
sex: new Promise(resolve => {
resolve("female")
}),
age: new Promise(resolve => {
resolve(18)
}),
});
ps.then(res => {
console.log(res.name);
console.log(res.sex);
console.log(res.age);
}).catch(err => console.log(err))
- 异步使用
import { PromiseAll } from './index'
(async () => {
// 异步使用
const res = await PromiseAll({
name: new Promise(resolve => {
resolve("bing")
}),
sex: new Promise(resolve => {
resolve("female")
}),
age: new Promise(resolve => {
resolve(18)
}),
});
console.log('start');
console.log(res.name);
console.log(res.sex);
console.log(res.age);
console.log('end');
})()
3.12 color 计算类
import { Color } from './index'
// 随机获取 rgb 颜色
console.log(Color.random());
console.log(Color.random());
// 随机获取 rgba 颜色
console.log(Color.random(true));
console.log(Color.random(true));
3.13 download 文件下载类
import { Download } from './index'
// 隐藏文件
Download.instance()
.setBlobText(text)
.setCharset("utf-8") // default
.setExtension(".ignore")
.download();
// 分别设置文件和扩展
Download.instance()
.setBlobText(text)
.setFilename("downfile")
.setExtension(".md")
.download();
// 直接设置文件名,自动计算文件扩展
Download.instance()
.setBlobText(text)
.setFilename("xx.md")
.download();
// 设置扩展,并使用自动创建的文件名
Download.instance()
.setBlobText(text)
.setExtension(".md")
.generateFilename()
.download();
2.0.20
2 months ago
2.0.21
2 months ago
2.0.19
2 months ago
2.0.18
2 months ago
2.0.17
2 months ago
2.0.16
2 months ago
2.0.15
2 months ago
2.0.14
2 months ago
2.0.13
2 months ago
2.0.12
2 months ago
2.0.10
6 months ago
2.0.9
6 months ago
2.0.8
6 months ago
2.0.7
6 months ago
2.0.6
7 months ago
2.0.5
7 months ago
2.0.4
7 months ago
2.0.3
7 months ago
2.0.2
7 months ago
2.0.1
7 months ago