@wuipkg/utils
v1.0.5
Published
开箱即用的前端业务通用工具函数库集合。提供如格式化、对象操作、本地存储包装与树形结构处理等常用帮助函数。
Readme
@wuipkg/utils
开箱即用的前端业务通用工具函数库集合。提供如格式化、对象操作、本地存储包装与树形结构处理等常用帮助函数。
安装
pnpm install @wuipkg/utilsAPI 详细说明与用法示例
1. Common (基础通用)
| 方法名 / 常量名 | 类型定义 | 描述 |
| --- | --- | --- |
| isWechat | boolean | 当前是否为微信环境。 |
| isWeappWebView | boolean | 当前是否为微信小程序内嵌 WebView。 |
| splitString | (value: string, split: number[]) => string | 按指定的数字长度区间将字符串分割并插入空格。 |
| cardFormatter | (value: string) => string | 将银行卡号格式化,每4位增加一个空格。 |
| idNoFormatter | (value: string) => string | 将中国大陆身份证号格式化为标准的 18 位结构分隔。 |
| phoneFormatter | (value: string) => string | 将手机号码格式化为 xxx xxxx xxxx。 |
| toRecord | <T extends object, K extends keyof T>(array: T[], key: K) => Record<T[K], T> | 将对象数组转成以指定特定枚举键索引的 Map 对象。 |
| safeExecuteSync | <R = unknown, E = unknown>(fn: () => R) => [R, E] | 捕获可能出现 Throw Error 的同步执行代码,避免阻断程序,返回元组 [返回值, 异常]。 |
环境探测与格式化示例:
import {
isWechat,
phoneFormatter,
cardFormatter,
splitString
} from '@wuipkg/utils'
if (!isWechat) {
console.log('当前非微信游览器!')
}
// 格式化测试
console.log(phoneFormatter('13800138000')) // 138 0013 8000
console.log(cardFormatter('6222021000123456789')) // 6222 0210 0012 3456 789
console.log(splitString('ABCDEFGHI', [3, 4])) // ABC DEFG HI对象字典转换示例 (toRecord):
import { toRecord } from '@wuipkg/utils'
const userList = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
const dic = toRecord(userList, 'id')
// 输出:{ '1': { id: 1, name: 'Alice' }, '2': { id: 2, name: 'Bob' } }
console.log(dic[1].name) // 'Alice'安全执行示例 (safeExecuteSync):
import { safeExecuteSync } from '@wuipkg/utils'
const [parsedObject, err] = safeExecuteSync(() => JSON.parse('{x}'))
if (err) {
console.log('格式错误,但主线程程序不会挂掉!') // 被捕捉
}2. Storage (缓存处理)
| 方法名 / 类 | 类型定义 | 描述 |
| --- | --- | --- |
| setCookie | (cname: string, cvalue: any, exdays: number) => void | 设置指定有效天数的 Cookie。 |
| getCookie | (cname: string) => string | 获取特定 Key 的 Cookie 值。 |
| Storage | class Storage(config: StorageConfig) | 代理 Web Storage 并提供了内置的前缀隔绝以及超时清理特性。 |
Storage & Cookie 使用示例:
import { setCookie, getCookie, Storage } from '@wuipkg/utils'
// 保存持续 7 天的 Cookie
setCookie('TOKEN', 'eyJhb...', 7)
const token = getCookie('TOKEN')
// 初始化高级安全本地存储管理器(给所有键自动加前缀以免业务数据覆写混乱)
const localManager = new Storage({ prefixKey: 'MY_APP_' })
// 不管是 Object 或是其它结构均可原样抛进、取出
localManager.set('userAction', { count: 1 })
const action = localManager.get('userAction')
// => { count: 1 } (底层存储在 localStorage 上的真实键为 "MY_APP_userAction")3. Tree (树形变换操作)
| 方法名 | 类型定义 | 描述 |
| --- | --- | --- |
| clipTree | <T>(tree: T[], condition: (node: T) => boolean, childrenKey?: string) => T[] | 剪枝/裁剪树形数据,通过给定的 condition 方法递归删除不满足条件的级联节点。 |
Tree 树裁剪示例:
import { clipTree } from '@wuipkg/utils'
const orgTree = [
{
id: 1, name: 'A 部', status: 'valid',
children: [
{ id: 2, name: 'A-1 组', status: 'invalid' }
]
}
]
// 剔除掉所有非 'valid' 的末端枝叶
const activeOrgs = clipTree(orgTree, (node) => node.status === 'valid', 'children')
// 运行后节点 2 会被删除。
console.log(activeOrgs)