Skip to content

对象工具 API

默认导出为 ObjectUtils

使用指引(做什么、何时用)

  • 防抖(debounce):输入搜索/自动保存,停顿达到 wait 毫秒才执行,减少无效请求
  • 节流(throttle):滚动/Resize 等高频事件,固定频率执行,提升性能
  • 一次性执行(once):避免重复初始化或注册,保证只执行一次
  • 延时(sleep):异步流程中插入等待,便于演示或控制节奏
  • 重试(retry):网络抖动时重试异步函数,配合 Http 使用

导入

ts
import { ObjectUtils } from 'nex-lib';

防抖(debounce)

  • 功能:在持续触发的事件中,只有停顿达到 wait 毫秒后才执行一次(常用于输入搜索)
  • 参数:fn(要延迟执行的函数),wait(毫秒)
  • 返回值:包装后的函数,直接用于事件回调
js
import { debounce } from 'nex-lib'
const run = debounce((q) => console.log('search:', q), 300)
document.querySelector('#input').addEventListener('input', (e) => run(e.target.value))
ts
import { debounce } from 'nex-lib'
const run = debounce((q: string) => console.log('search:', q), 300)
// 组件中只初始化一次,然后在 onInput 中调用 run(value)
text
不要在每次事件触发时重新创建 debounce;应在初始化时创建并复用同一个包装函数。

节流(throttle)

  • 功能:在持续触发的事件中,按固定频率(每 wait 毫秒)最多执行一次(常用于滚动或窗口大小变化)
  • 参数:fn(要限频执行的函数),wait(毫秒)
  • 返回值:包装后的函数,直接用于事件回调
js
import { ObjectUtils } from 'nex-lib'
const onScroll = ObjectUtils.throttle(() => {
  console.log('scroll Y:', window.scrollY)
}, 200)
window.addEventListener('scroll', onScroll)
ts
import { ObjectUtils } from 'nex-lib'
const onResize = ObjectUtils.throttle(() => {
  const w = window.innerWidth, h = window.innerHeight
  console.log('viewport:', w, h)
}, 200)
window.addEventListener('resize', onResize)
text
本实现包含尾随调用:在间隔内最后一次触发会在时间到达后再执行一次。

deepMerge<T, S>(target: T, source: S): T & S

  • 递归合并对象,返回新对象。
ts
ObjectUtils.deepMerge({ a: 1, nest: { x: 1 } }, { b: 2, nest: { y: 2 } });
// { a:1, b:2, nest:{ x:1, y:2 } }

一次性执行(once)

  • 功能:确保函数只执行一次,常用于初始化
ts
const init = ObjectUtils.once(() => {
  // 只会执行一次的初始化逻辑
})
init(); init(); // 第二次不执行

延时(sleep)

  • 功能:等待指定毫秒,配合 async/await
ts
await ObjectUtils.sleep(500)

重试(retry)

  • 功能:对返回 Promise 的函数进行重试,适合偶发网络错误
ts
await ObjectUtils.retry(async () => {
  // 可能失败的异步操作
}, 3, 200)

deepEqual(obj1, obj2): boolean

  • 深度比较(基于 JSON 序列化)。
ts
ObjectUtils.deepEqual({ a: 1 }, { a: 1 }); // true

judgeTypes(target): string

  • 返回 string|number|boolean|object|function|date|regexp|error|null|undefined|array 等。
ts
ObjectUtils.judgeTypes([]); // 'array'

treeFilter(tree, func)

  • 按条件过滤树结构,保留命中节点与其子树。
ts
ObjectUtils.treeFilter(menu, node => node.visible);

filterAndRecurse(arr, predicate)

  • 递归过滤并返回新数组。
ts
ObjectUtils.filterAndRecurse(list, item => item.enabled);

keys(obj): string[] / values(obj): any[]

ts
ObjectUtils.keys({ a: 1 });   // ['a']
ObjectUtils.values({ a: 1 }); // [1]

deepClone(obj)

  • 深拷贝对象/数组/日期等
ts
const src = { a: 1, b: { c: [1,2,3] } }
const cloned = ObjectUtils.deepClone(src)

groupBy(arr, keyOrFn)

  • 按字段或函数分组,返回 { [key]: T[] }
ts
ObjectUtils.groupBy([
  { id: 1, type: 'a' },
  { id: 2, type: 'b' },
  { id: 3, type: 'a' },
], 'type') // { a:[...], b:[...] }

uniqBy(arr, keyOrFn)

  • 按字段或函数去重,保留首个出现
ts
ObjectUtils.uniqBy([
  { id: 1 }, { id: 2 }, { id: 1 }
], 'id') // [{ id:1 }, { id:2 }]

Released under the ISC License.