Skip to content

GreatAuk/utopia-utils

Repository files navigation

Utopia-Utils

NPM Version License

目录

安装

# 核心包,包含绝大部分 utils
pnpm add @utopia-utils/core

# 仅安装 Vue Composables (Vue 3)
pnpm add @utopia-utils/vueuse

# 仅安装 DOM 相关 utils
pnpm add @utopia-utils/dom

# 仅安装树结构相关 utils
pnpm add @utopia-utils/tree

# 仅安装类型判断相关 utils
pnpm add @utopia-utils/share

# 仅安装 CLI 工具
pnpm add @utopia-utils/cli

API 参考

数组

对象

函数

Promise

字符串

数值

URL

编解码

  • base64ToFile: base64 转 File, 如图片裁剪时,我们获取到的是 base64,但上传接口一般需要 formData 上传。source
  • toBase64: 将 File | Blob | imgUrl 转 base64。source

树结构

Vue Composables

  • useSmsCountdown: 短信验证码倒计时的 Vue composable 函数,提供完整的验证码发送倒计时功能。支持自定义倒计时时长、控制发送状态、自定义显示文本等。source
  • useTable: 表格状态管理 Hook 的简单封装,减少模板代码。提供分页、排序、过滤和搜索功能的完整解决方案。支持简单搜索模式(实时搜索)和高级搜索模式(手动搜索)。source
  • useFakeProgress: 可控的假进度条 Hook,支持自动递增、手动控制、自定义递增算法,提供进度变化/完成回调,适用于上传、异步加载等场景。source
  • useDelayedLoading: 延迟显示与最小显示时间控制的 loading 状态管理 Hook,可有效避免短请求导致的 loading 闪烁问题。source
  • useDeferredToggle: 传入原始 open / hide 方法,返回带防闪烁逻辑的新 open / hide。。source

DOM

浏览器环境

类型判断

CLI 工具

杂项


废弃的 API


第三方库

@utopia-utils/core 重新导出了下面这些优秀的第三方库,方便直接使用。

  • debounce: 函数防抖。
  • throttle: 函数节流。
  • js-cookie: 轻量级的浏览器 cookie 操作库。
  • mitt: 仅 200 字节的函数式事件发布/订阅库,类型安全。
  • deepmerge: 深度合并对象的库。
  • number-precision: 解决浮点数计算精度问题的库。

推荐的工具库

  • file-saver: An HTML5 saveAs() FileSaver implementation.
  • zod: TypeScript-first schema validation with static type inference.
  • dayjs: ⏰ Day.js 2kB immutable date-time library alternative to Moment.js with the same modern API.
  • any-rule: 常用正则大全。
  • fast-deep-equal: The fastest deep equality check with Date, RegExp and ES6 Map, Set and typed arrays support.
  • big.js: 一个小型,快速的 JavaScript 库,用于任意精度的十进制算术运算。
  • browser-image-compression: Javascript module to be run in the web browser for image compression.
  • hashids: generate YouTube-like ids from numbers.

defineDictionary

定义业务字典, 类型安全

// at src/constant.ts
const { get_MUSIC_TYPE_KEYS, get_MUSIC_TYPE_KV, get_MUSIC_TYPE_MAP, get_MUSIC_TYPE_MAP_BY_KEY, get_MUSIC_TYPE_MAP_BY_VALUE, get_MUSIC_TYPE_OPTIONS, get_MUSIC_TYPE_VALUES, get_MUSIC_TYPE_VK } = defineDictionary([
  {
    key: 'POP',
    value: 1,
    label: '流行音乐',
    color: 'red',
  },
  {
    key: 'ROCK',
    value: 2,
    label: '摇滚音乐',
    color: 'blue',
  },
] as const, 'MUSIC_TYPE') // !!! 必须使用 as const 来保证类型安全

export const MUSIC_TYPE_KEYS = get_MUSIC_TYPE_KEYS()
// ['POP', 'ROCK']
export const MUSIC_TYPE_VALUES = get_MUSIC_TYPE_VALUES()
// [1, 2]
export const MUSIC_TYPE_KV = get_MUSIC_TYPE_KV()
// { POP: 1, ROCK: 2 }
export const MUSIC_TYPE_VK = get_MUSIC_TYPE_VK()
// { 1: 'POP', 2: 'ROCK' }
export const MUSIC_TYPE_MAP_BY_KEY = get_MUSIC_TYPE_MAP_BY_KEY()
// {
//   POP: { key: 'POP', value: 1, label: '流行音乐', color: 'red' },
//   ROCK: { key: 'ROCK', value: 2, label: '摇滚音乐', color: 'blue' }
// }
export const MUSIC_TYPE_MAP_BY_VALUE = get_MUSIC_TYPE_MAP_BY_VALUE()
// {
//   1: { key: 'POP', value: 1, label: '流行音乐', color: 'red' },
//   2: { key: 'ROCK', value: 2, label: '摇滚音乐', color: 'blue' }
// }
export const MUSIC_TYPE_MAP = get_MUSIC_TYPE_MAP()
// { POP: 1, ROCK: 2 }
export const MUSIC_TYPE_OPTIONS = get_MUSIC_TYPE_OPTIONS()
// [
//   { key: 'POP', value: 1, label: '流行音乐', color: 'red' },
//   { key: 'ROCK', value: 2, label: '摇滚音乐', color: 'blue' }
// ]
createEnumFromOptions

已废弃, 请使用 defineDictionary 代替。

通过 options 自动生成对应的 enum, 后期只需要维护 options类型安全

// example
const optionsLevel = [
  {
    value: 0,
    label: 'level1',
  },
  {
    value: 1,
    label: 'level2',
  },
] as const // 必须使用 as const 来保证类型安全

const enumLevel = createEnumFromOptions(optionsLevel)
console.log(enumLevel.level1) // 0
console.log(enumLevel['0']) // 'level1'
console.log(enumLevel)
// {
//   "0": "level1",
//   "1": "level2",
//   "level1": 0,
//   "level2": 1
// }
retry

重试函数(如果函数抛出错误)直到成功或者达到最大重试次数。

let callNum = 0
function fn() {
  callNum++
  return Promise.reject(new Error('foo'))
}
const [err, res] = await retry(fn, 2, (attemptTime) => {
  return attemptTime * 5
})
// err 是 Error, res 是 null, callNum 是 3
// 总执行时间 >= 15ms (5ms + 10ms)

Tree Utils

所有的 Tree utils 支持自定义 fieldNames

export interface FieldNames {
  id?: string
  children?: string
  parentId?: string
}
breadthFirstTraverse

广度优先遍历。

img

// example
const tree = [
  {
    name: 'a',
    Children_: [
      { name: 'b' },
    ],
  },
  {
    name: 'c',
  },
]

breadthFirstTraverse(tree, node => console.log(node.name), {
  fieldNames: {
    children: 'Children_', // 默认为 'children'
  },
})
// output 'a', 'c', 'b'
treeFindNode

查找符合条件的单个节点或多个节点,通过广度优先遍历查找。

// example
const tree = [
  {
    name: 'a',
    children: [
      { name: 'b' },
    ],
  }
]

const res = treeFindNode(tree, node => node.name === 'b') // res is [{ name: 'b' }]
buildTreeFromList

列表结构转树结构。

// example
const list = [
  { uid: '1', title: 'node 1', pid: '' },
  { uid: '1-1', title: 'node 1-1', pid: '1' },
  { uid: '1-2', title: 'node 1-2', pid: '1' },
  { uid: '1-1-1', title: 'node 1-1-1', pid: '1-1' },
]

interface TreeNode {
  key: string
  title: string
  children: TreeNode[]
  pid: string
}

const tree = buildTreeFromList<TreeNode>(list, {
  listFieldNames: { id: 'uid', parentId: 'pid' },
  treeFieldNames: { id: 'key', parentId: 'pid', children: 'children' },
})
flattenTree

打平,树结构转列表结构。

// example
const tree = {
  id: 1,
  children: [
    {
      id: 2,
    },
  ],
}
const list = flattenTree(tree)
console.log(list)
// output
// [
//   {
//     "id": 1,
//     "children": [
//       {
//         "id": 2,
//       },
//     ],
//   },
//   {
//     "id": 2,
//   },
// ]
treeFindPath

查打符合条件节点的路径。

// example
const tree = [
  {
    name: 'a',
    children: [
      { name: 'b' },
    ],
  },
  {
    name: 'c',
  },
]

const path = treeFindPath(tree, node => node.name === 'b')
console.log(path?.map(v => v.name)) // ['a', 'b']
treeFilterNode

过滤不符合条件的树节点。

const tree = [
  {
    id: 'root',
    children: [
      {
        id: 'child1',
      },
      {
        id: 'child2',
      },
    ],
  },
]
treeFilterNode(tree, node => node.id.includes('1'))
// output
// [
//   {
//     children: [
//       {
//         id: 'child1',
//       },
//     ],
//     id: 'root',
//   },
// ]

License

MIT

About

Collection of common utils. Tree-shakable ESM. Typesafe.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages