c-utility
v1.0.5
Published
Common tool functions
Maintainers
Readme
c-utility
一个 TypeScript 工具库,提供常见的数组、字符串等工具函数。
安装
npm install c-utility
# 或
yarn add c-utility2.3 快速开始
## 快速开始
```typescript
import { uniqueObjects } from 'c-utility';
const data = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alice' }
];
const uniqueData = uniqueObjects(data, 'id');
console.log(uniqueData); // 输出: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]2.4 API 文档
## API
### `uniqueObjects<T>(arr: T[], key?: keyof T | ((item: T) => string)): T[]`
- **参数**:
- `arr`: 包含对象的数组
- `key`: 可选,用于生成唯一标识的对象属性名或自定义函数
- **返回值**:去重后的数组
- **示例**:
```typescript
// 按 id 去重
const uniqueById = uniqueObjects(users, 'id');
// 按复合键去重
const uniqueByComposite = uniqueObjects(orders, item =>
`${item.userId}-${item.productId}`
);
## 防抖 --节流 函数
```typescript
import { debounce, throttle } from 'c-utility';
// 示例:搜索框输入防抖
const searchInput = document.getElementById('search-input');
// 定义函数类型
const searchFunction = (value: string): void => {
console.log('Searching for:', value);
// 执行搜索逻辑
};
// 创建防抖函数,延迟 300ms
const debouncedSearch = debounce(searchFunction, 300);
// 监听输入事件
searchInput?.addEventListener('input', (e) => {
debouncedSearch(e.target.value);
});
// 示例:滚动事件节流
const handleScroll = (): void => {
console.log('Scroll position:', window.scrollY);
// 执行滚动相关逻辑
};
// 创建节流函数,限制每 200ms 执行一次
const throttledScroll = throttle(handleScroll, 200);
// 监听滚动事件
window.addEventListener('scroll', throttledScroll);
## 深克隆函数使用示例
import {deepClone } from 'c-utility';
// 示例 1: 简单对象克隆
const simpleObj = {
name: 'John',
age: 30,
hobbies: ['reading', 'coding']
};
const clonedSimpleObj = deepClone(simpleObj);
console.log('示例 1 - 简单对象克隆:');
console.log(clonedSimpleObj); // { name: 'John', age: 30, hobbies: ['reading', 'coding'] }
console.log(simpleObj === clonedSimpleObj); // false (引用不同)
console.log(simpleObj.hobbies === clonedSimpleObj.hobbies); // false (嵌套数组也被深克隆)2.5 贡献指南
## 贡献
1. Fork 仓库
2. 创建你的特性分支 (`git checkout -b feature/your-feature`)
3. 提交更改 (`git commit -am 'Add some feature'`)
4. 将更改推送到分支 (`git push origin feature/your-feature`)
5. 提交 Pull Request许可证
MIT © defu
