# iota-utils **Repository Path**: coder-farmer/iota-utils ## Basic Information - **Project Name**: iota-utils - **Description**: 自用的函数工具包,里面主要有存储操作,树结构操作,数组操作,类型判断,UUID生成 等工具 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-03-17 - **Last Updated**: 2025-09-03 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # IOTA Utils 实用的 JavaScript/TypeScript 工具库。 ## 安装 ```bash npm install iota-utools ``` ## 功能模块 ### 类型判断 ```typescript import { getTypeof, isArray, isBoolean, isString, isNumber, isObject, isFunction, isMap, isSet, isSymbol } from 'iota-utils'; // 获取数据类型 getTypeof([]); // 'array' getTypeof({}); // 'object' getTypeof(''); // 'string' // 类型判断示例 isArray([1, 2, 3]); // true isBoolean(false); // true isString('hello'); // true isNumber(123); // true isObject({}); // true isFunction(() => {}); // true isMap(new Map()); // true isSet(new Set()); // true isSymbol(Symbol('test')); // true ``` ### Storage 操作 #### Storage 监听 ```typescript import { monitorStorage } from 'iota-utils'; // 开始监听存储变化 const cleanup = monitorStorage({ type: 'both', // 监听 local 和 session storage emitUnchanged: false, // 值未变化时不触发 onError: (error) => console.error('Storage error:', error) }); // 监听 localStorage 变化 window.addEventListener('local', (e) => { const event = e; console.log('Local storage changed:', { key: event.key, newValue: event.newValue, oldValue: event.oldValue, storageArea: event.storageArea }); }); // 监听 sessionStorage 变化 window.addEventListener('session', (e) => { const event = e; console.log('Session storage changed:', { key: event.key, newValue: event.newValue, oldValue: event.oldValue, storageArea: event.storageArea }); }); // 清理监听器 cleanup(); ``` #### localStorage 操作 ```typescript import { setLocalStorage, getLocalStorage, removeLocalStorageKey } from 'iota-utils'; // 存储数据 setLocalStorage('user', { name: 'John', age: 30 }); // 获取数据 const user = getLocalStorage('user'); // { name: 'John', age: 30 } // 删除数据 removeLocalStorageKey('user'); // 删除多个键 removeLocalStorageKey('key1', 'key2', 'key3'); ``` #### sessionStorage 操作 ```typescript import { setSessionStorage, getSessionStorage, removeSessionStorageKey } from 'iota-utils'; // 存储数据 setSessionStorage('tempData', { id: 123 }); // 获取数据 const data = getSessionStorage('tempData'); // { id: 123 } // 删除数据 removeSessionStorageKey('tempData'); // 删除多个键 removeSessionStorageKey('temp1', 'temp2'); ``` ### 文件操作 #### 文件下载 ```typescript import { downFile, downStream } from 'iota-utils'; // 下载文件 downFile('Hello, World!', 'test.txt', 'text/plain;charset=utf-8'); // 下载流文件 downStream( 'https://api.example.com/files/123', 'document.pdf', 'Bearer token123', { param1: 'value1' } ); ``` ### 数组处理 ```typescript import { uniqueArrayByProperty, arraySlice } from 'iota-utils'; // 根据属性去重 const users = [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 1, name: 'John' } ]; const uniqueUsers = uniqueArrayByProperty(users, 'id'); // 结果: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }] // 数组切片 const numbers = [1, 2, 3, 4, 5, 6]; const sliced = arraySlice(numbers, 2); // 结果: [[1, 2], [3, 4], [5, 6]] ``` ### 对象处理 ```typescript import { flattenObject, unflattenObject } from 'iota-utils'; // 对象扁平化 const nested = { name: 'John', info: { age: 30, address: { city: 'New York' } } }; const flat = flattenObject(nested); // 结果: { // 'name': 'John', // 'info.age': 30, // 'info.address.city': 'New York' // } // 扁平对象还原 const restored = unflattenObject(flat); // 结果: 与原始 nested 对象结构相同 ``` ### 字符串处理 ```typescript import { format, templateReplace, decodeParams, encodeParams } from 'iota-utils'; // 字符串格式化 const formatted = format('Hello, {0}!', 'World'); // 结果: 'Hello, World!' // 模板字符串替换 const template = 'Hello, ((name))!'; const result = templateReplace(template, { name: 'John' }); // 结果: 'Hello, John!' // 查询字符串解析 const params = decodeParams('name=John&age=30'); // 结果: { name: 'John', age: '30' } // 对象转查询字符串 const query = encodeParams({ name: 'John', age: 30 }); // 结果: 'name=John&age=30' ``` ### 树形结构处理 ```typescript import { toFlatTree, toTreeFlat, deepClone, deleteTreeNode, findTreeNode, fuzzySearchTree } from 'iota-utils'; const tree = { id: 1, title: 'Root', children: [ { id: 2, title: 'Child 1', children: [] }, { id: 3, title: 'Child 2', children: [] } ] }; // 树转扁平结构 const flat = toFlatTree(tree); // 扁平结构转树 const restored = toTreeFlat(flat); // 深拷贝 const cloned = deepClone(tree); // 删除节点 const newTree = deleteTreeNode(tree, 2); // 查找节点 const node = findTreeNode(tree, 2, 'id'); // 模糊搜索 const searchResult = fuzzySearchTree(tree, 'Child', 'title'); ``` ### 异步处理 ```typescript import { awitto } from 'iota-utils'; // 异步函数错误处理 async function fetchData() { const [error, result] = await awitto(fetch('https://api.example.com/data')); if (error) { console.error('Failed:', error); return; } console.log('Success:', result); } // 异步函数的错误处理 - 更多示例 async function examples() { // 处理API请求 const [apiError, apiData] = await awitto(fetch('api/data')); // 处理文件读取 const [fileError, fileData] = await awitto(readFile('example.txt')); // 处理数据库操作 const [dbError, dbResult] = await awitto(database.query('SELECT * FROM users')); // 链式调用 const [err1, data] = await awitto( fetch('api/data') .then(res => res.json()) ); } ``` ### 文件上传 ```typescript import { uploadSlice } from 'iota-utils'; // 切片上传 const file = new File(['content'], 'test.txt'); const config = { // 上传配置 }; uploadSlice( file, 1024 * 1024, // 1MB 切片大小 'https://api.example.com/upload', (progress) => { console.log(`上传进度:${progress}%`); }, config ) .then(({ finish, failedSlices }) => { if (finish) { console.log('上传完成!'); } else { console.log('部分切片上传失败:', failedSlices); } }) .catch((error) => { console.error('上传失败:', error); }); ``` ### UUID 生成 ```typescript import { generateUUID, generateString } from 'iota-utils'; // 生成标准 UUID const uuid = generateUUID(); // 结果示例: "550e8400-e29b-41d4-a716-446655440000" // 使用自定义模板生成 UUID const customUUID = generateUUID("xxxx-yyyy-zzzz"); // 结果将按照模板格式生成 // 生成字母开头的随机字符串 const randomString = generateString(); // 默认长度为 8 // 结果示例: "Ak7x9Pq2" // 指定长度生成字符串 const longString = generateString(16); // 结果示例: "Bw3mK9nX5vY2pQ8r" ``` ### 日期处理 ```typescript import { generateCalendar } from 'iota-utils'; // 生成指定年月的日历数据 const calendar = generateCalendar(2025, 8); // 返回当月的日历数据,包括: // 1. 上月末尾需要显示的日期 // 2. 当月所有日期 // 3. 下月开头需要显示的日期 // 日历数据示例 [ { date: Date, // 日期对象 meta: { year: 2025, // 年份 month: 8, // 月份(1-12) day: 15, // 日期(1-31) dayOfWeek: "Friday", // 星期几 type: "current", // 日期类型:'prev' | 'current' | 'next' formattedDate: "2025-08-15" // 格式化的日期 } }, // ... 其他日期数据 ] ``` ### 工具函数 ```typescript import { copyText, sleep } from 'iota-utils'; // 复制文本 await copyText('Hello, World!'); // 延时执行 await sleep(1000); // 暂停 1 秒 ``` ## 许可证 MIT