2.2.10 • Published 9 months ago

@wwjkhxc/utils v2.2.10

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

@wwjkhxc/utils

一个全面的 TypeScript 工具函数库。

安装

npm install @wwjkhxc/utils

2.2.9

  • 新增多个工具函数模块
  • 优化现有功能
  • 更新文档

2.2.8

-css style

2.2.7

-bug

2.2.6

-bug

2.2.5

-bug

2.2.4

-image

2.2.3

-bug

2.2.2

-A molecule

2.2.1

-A function

2.2.0

-Bug css

2.1.9

-Bug css

2.1.8

-Vue and React

1.1.8

-version

1.1.7

-version

1.1.6

-README

1.1.5

-bug

1.1.4

-bug

1.1.2

-React compatibility Vue3

0.1.2

-A Template Ruler

0.0.2

-Add Function

0.0.1

-Init

功能模块

1. 数组工具 (arrayUtils)

import { arrayUtils } from '@wwjkhxc/utils';

// 数组去重
arrayUtils.unique([1, 2, 2, 3]); // [1, 2, 3]

// 数组分组
arrayUtils.groupBy([
  { type: 'A', value: 1 }, 
  { type: 'B', value: 2 }
], 'type'); // { A: [...], B: [...] }

// 数组扁平化
arrayUtils.flatten([1, [2, 3], [4]]); // [1, 2, 3, 4]

// 数组交集
arrayUtils.intersection([1, 2], [2, 3]); // [2]

// 数组分块
arrayUtils.chunk([1, 2, 3, 4], 2); // [[1, 2], [3, 4]]

2. 对象工具 (objectUtils)

import { objectUtils } from '@wwjkhxc/utils';

// 深度合并
objectUtils.deepMerge(obj1, obj2);

// 对象扁平化
objectUtils.flatten({ a: { b: 1 } }); // { 'a.b': 1 }

// 深度克隆
objectUtils.deepClone(obj);

// 深度冻结
objectUtils.deepFreeze(obj);

3. 字符串工具 (stringUtils)

import { stringUtils } from '@wwjkhxc/utils';

// 生成UUID
stringUtils.uuid();

// 字符串截断
stringUtils.truncate('Hello World', 5); // 'He...'

// 驼峰命名转换
stringUtils.camelCase('hello-world'); // 'helloWorld'

4. 日期工具 (dateUtils)

import { dateUtils } from '@wwjkhxc/utils';

// 格式化日期
dateUtils.format(new Date(), 'YYYY-MM-DD');

// 相对时间
dateUtils.relativeTime(new Date('2023-01-01'));

// 获取日期范围
dateUtils.getDateRange(startDate, endDate);

5. 性能工具 (performanceUtils)

import { performanceUtils } from '@wwjkhxc/utils';

// 函数防抖
const debouncedFn = performanceUtils.debounce(fn, 300);

// 函数节流
const throttledFn = performanceUtils.throttle(fn, 300);

// 资源预加载
performanceUtils.preload(['image.jpg', 'script.js']);

6. 验证工具 (validationUtils)

import { validationUtils } from '@wwjkhxc/utils';

// 邮箱验证
validationUtils.isEmail('test@example.com');

// 手机号验证
validationUtils.isPhone('13800138000');

// 密码强度检查
validationUtils.checkPasswordStrength('Password123');

7. 设备工具 (deviceUtils)

import { deviceUtils } from '@wwjkhxc/utils';

// 获取设备信息
const info = deviceUtils.getDeviceInfo();

// 获取屏幕信息
const screen = deviceUtils.getScreenInfo();

// 特性检测
await deviceUtils.featureDetection.webP();

8. 网络工具 (networkUtils)

import { networkUtils } from '@wwjkhxc/utils';

// 获取网络状态
const netInfo = networkUtils.getNetworkInfo();

// 监听网络变化
const monitor = networkUtils.createNetworkMonitor();
monitor.onChange(info => console.log(info));

// 测试服务器延迟
const ping = await networkUtils.pingServer('https://api.example.com');

9. WebSocket工具 (websocketUtils)

import { websocketUtils } from '@wwjkhxc/utils';

const ws = websocketUtils.createWebSocketClient('wss://example.com', {
  autoReconnect: true,
  heartbeatInterval: 30000
});

ws.onMessage(data => console.log(data));
ws.send('Hello');

10. 错误处理工具 (errorUtils)

import { errorUtils } from '@wwjkhxc/utils';

// 自定义错误
throw new errorUtils.createCustomError('错误信息', 'ERROR_CODE');

// 错误重试
await errorUtils.retry(async () => {
  // 异步操作
}, {
  maxAttempts: 3,
  delay: 1000
});

11. 数据转换工具 (convertUtils)

import { convertUtils } from '@wwjkhxc/utils';

// XML转JSON
const json = convertUtils.xmlToJson(xmlString);

// JSON转XML
const xml = convertUtils.jsonToXml(jsonObject);

// CSV转JSON
const jsonArray = convertUtils.csvToJson(csvString);

// JSON转CSV
const csv = convertUtils.jsonToCsv(jsonArray);

12. 数学计算工具 (mathUtils)

import { mathUtils } from '@wwjkhxc/utils';

// 精确计算
mathUtils.precise.add(0.1, 0.2);    // 0.3
mathUtils.precise.multiply(0.1, 0.2); // 0.02

// 角度转换
mathUtils.toRadians(90);  // π/2
mathUtils.toDegrees(Math.PI); // 180

// 贝塞尔曲线计算
mathUtils.bezier(0.5, [[0,0], [0.5,1], [1,0]]);

13. 颜色处理工具 (colorUtils)

import { colorUtils } from '@wwjkhxc/utils';

// RGB转十六进制
colorUtils.rgbToHex(255, 0, 0); // '#ff0000'

// 十六进制转RGB
colorUtils.hexToRgb('#ff0000'); // { r: 255, g: 0, b: 0 }

// 生成渐变色
colorUtils.createGradient('#ff0000', '#0000ff', 5);

14. 加密工具 (cryptoUtils)

import { cryptoUtils } from '@wwjkhxc/utils';

// MD5加密
await cryptoUtils.md5('hello'); 

// SHA-256加密
await cryptoUtils.sha256('hello');

// AES加密/解密
const encrypted = await cryptoUtils.aesEncrypt('hello', 'key');
const decrypted = await cryptoUtils.aesDecrypt(encrypted, 'key');

15. 文件工具 (fileUtils)

import { fileUtils } from '@wwjkhxc/utils';

// 获取文件扩展名
fileUtils.getExtension('image.jpg'); // 'jpg'

// 获取MIME类型
fileUtils.getMimeType('image.jpg'); // 'image/jpeg'

// 文件大小格式化
fileUtils.formatSize(1024); // '1 KB'

// 文件转Base64
await fileUtils.toBase64(file);

16. DOM操作工具 (domUtils)

import { domUtils } from '@wwjkhxc/utils';

// 元素选择
const el = domUtils.$('#app');
const els = domUtils.$$('.item');

// 事件处理
domUtils.on(el, 'click', handler);
domUtils.off(el, 'click', handler);

// 样式操作
domUtils.addClass(el, 'active');
domUtils.removeClass(el, 'active');
domUtils.css(el, 'backgroundColor', '#fff');

17. 数据结构工具 (dataStructureUtils)

import { dataStructureUtils } from '@wwjkhxc/utils';

// 创建优先队列
const queue = dataStructureUtils.createPriorityQueue((a, b) => a - b);
queue.enqueue(3);
queue.enqueue(1);
queue.dequeue(); // 1

// 创建Trie树
const trie = dataStructureUtils.createTrie();
trie.insert('hello');
trie.search('hello'); // true

// 创建并查集
const uf = dataStructureUtils.createUnionFind(10);
uf.union(1, 2);
uf.connected(1, 2); // true

18. 国际化工具 (i18nUtils)

import { i18nUtils } from '@wwjkhxc/utils';

// 创建i18n实例
const i18n = i18nUtils.createI18n({
  en: { hello: 'Hello {name}' },
  zh: { hello: '你好 {name}' }
}, 'en');

// 文本翻译
i18n.t('hello', { name: 'World' }); // 'Hello World'

// 切换语言
i18n.setLocale('zh');

19. 性能监控工具 (performanceMonitorUtils)

import { performanceMonitorUtils } from '@wwjkhxc/utils';

// 性能标记
performanceMonitorUtils.start('operation');
// ... 执行操作
const duration = performanceMonitorUtils.end('operation');

// 获取性能指标
const metrics = performanceMonitorUtils.getMetrics();

// 资源加载性能
const resources = performanceMonitorUtils.getResourceTiming();

20. 数据存储工具 (storageUtils)

import { storageUtils } from '@wwjkhxc/utils';

// 创建本地存储
const storage = storageUtils.createStorage('app');
storage.set('user', { name: 'John' }, 3600000); // 1小时过期
const user = storage.get('user');

// 创建内存缓存
const cache = storageUtils.createCache({ maxSize: 100, ttl: 3600000 });
cache.set('key', 'value');
const value = cache.get('key');

21. 算法工具 (algorithmUtils)

import { algorithmUtils } from '@wwjkhxc/utils';

// 二分查找
algorithmUtils.binarySearch([1, 2, 3, 4, 5], 3); // 2

// 快速排序
algorithmUtils.quickSort([3, 1, 4, 1, 5]); // [1, 1, 3, 4, 5]

// 归并排序
algorithmUtils.mergeSort([3, 1, 4, 1, 5]); // [1, 1, 3, 4, 5]

22. 图形处理工具 (graphicsUtils)

import { graphicsUtils } from '@wwjkhxc/utils';

// 创建Canvas上下文
const ctx = graphicsUtils.createContext(800, 600);

// 图片压缩
const compressed = await graphicsUtils.compressImage(file, {
    maxWidth: 800,
    quality: 0.8
});

// 图片裁剪
const cropped = await graphicsUtils.cropImage(file, {
    x: 0,
    y: 0,
    width: 100,
    height: 100
});

23. 网络请求工具 (requestUtils)

import { requestUtils } from '@wwjkhxc/utils';

// 创建请求客户端
const client = requestUtils.createClient({
    headers: { 'Content-Type': 'application/json' }
});

// 发送请求
const data = await client.get('/api/users');
await client.post('/api/users', { name: 'John' });
await client.put('/api/users/1', { name: 'John' });
await client.delete('/api/users/1');

组件

Ruler 标尺组件

// Vue版本
import { VueRuler } from '@wwjkhxc/utils';
// React版本
import { ReactRuler } from '@wwjkhxc/utils';

// 使用示例
<VueRuler :width="800" :height="30" />
<ReactRuler width={800} height={30} />

更新日志

开发指南

安装依赖

npm install

开发

npm run dev

构建

npm run build

发布

#发布前请确保已经登录:
npm login --registry=https://registry.npmjs.com

# 发布补丁版本
npm run publish:patch

# 发布次版本
npm run publish:minor

# 发布主版本
npm run publish:major

高级功能

链式调用

import { arrayUtils, objectUtils } from '@wwjkhxc/utils';

const result = arrayUtils
    .unique([1, 2, 2, 3])
    .map(x => x * 2)
    .filter(x => x > 2);

const merged = objectUtils
    .deepMerge(obj1, obj2)
    .transform(value => value * 2)
    .filter(value => value > 10);

自定义配置

// WebSocket配置
const ws = websocketUtils.createWebSocketClient('wss://example.com', {
    autoReconnect: true,
    maxReconnectAttempts: 5,
    reconnectDelay: 1000,
    heartbeatInterval: 30000,
    heartbeatMessage: 'ping'
});

// 存储配置
const storage = storageUtils.createStorage('app', {
    prefix: 'myapp_',
    encryption: true,
    compression: true
});

// 请求客户端配置
const client = requestUtils.createClient({
    baseURL: 'https://api.example.com',
    timeout: 5000,
    headers: {
        'Authorization': 'Bearer token'
    },
    interceptors: {
        request: (config) => config,
        response: (response) => response
    }
});

最佳实践

错误处理

import { errorUtils } from '@wwjkhxc/utils';

// 使用错误边界
const result = await errorUtils.errorBoundary(
    async () => {
        // 可能抛出错误的操作
    },
    (error) => {
        // 错误处理
        return fallbackValue;
    }
);

// 使用重试机制
const result = await errorUtils.retry(
    async () => {
        // 可能失败的操作
    },
    {
        maxAttempts: 3,
        delay: 1000,
        backoff: 2,
        shouldRetry: (error) => error.code === 'NETWORK_ERROR'
    }
);

性能优化

import { performanceUtils, cacheUtils } from '@wwjkhxc/utils';

// 使用防抖
const debouncedSearch = performanceUtils.debounce(search, 300);

// 使用节流
const throttledScroll = performanceUtils.throttle(onScroll, 100);

// 使用缓存
const cache = cacheUtils.createCache({ maxSize: 100 });
const getData = async (key) => {
    const cached = cache.get(key);
    if (cached) return cached;
    
    const data = await fetchData(key);
    cache.set(key, data);
    return data;
};

贡献指南

  1. Fork 项目
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开 Pull Request

许可证

MIT

支持

如果这个项目对你有帮助,请给它一个星标 ⭐️

作者

wwjkhxc

鸣谢

感谢所有贡献者的付出!

2.2.10

9 months ago

2.2.8

10 months ago

2.1.9

10 months ago

2.2.1

10 months ago

2.2.0

10 months ago

2.2.3

10 months ago

2.2.2

10 months ago

2.2.5

10 months ago

2.2.4

10 months ago

2.2.7

10 months ago

2.1.8

10 months ago

2.2.6

10 months ago

0.1.2

10 months ago

1.1.8

10 months ago

1.1.7

10 months ago

1.1.6

10 months ago

1.1.4

10 months ago

1.1.3

10 months ago

1.1.2

10 months ago

0.0.2

10 months ago

0.0.1

10 months ago