# 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**: 1 - **Forks**: 0 - **Created**: 2023-03-17 - **Last Updated**: 2026-06-16 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # IOTA Utils ⚠️该项目为个人日常中使用的工具函数库,使用需谨慎,函数不定期进行修改、该工具库使用 JavaScript/TypeScript构建,使用请谨慎或注意更新日志。 ## 核心特性 - 🚀 **高性能**:优化的算法和数据结构 - 🔒 **类型安全**:完整的 TypeScript 支持 - 📦 **模块化**:按需导入,减少打包体积 - 🧪 **测试覆盖**:全面的单元测试 - 📚 **文档完善**:详细的使用说明和示例 ## 安装 ```bash npm install iota-utools # 或 yarn add iota-utools # 或 pnpm add iota-utools ``` ## 快速开始 ```typescript import { getTypeof, setLocalStorage, catchError } from "iota-utils"; // 类型判断 console.log(getTypeof([])); // 'array' // 存储操作 setLocalStorage("user", { name: "John" }); // 错误处理 const [err, data] = await catchError(async () => { return await fetch("/api/data").then((r) => r.json()); }); ``` ## 功能模块 | 模块 | 说明 | 函数数量 | | --------------------------------------- | ------------ | -------- | | [array](#-数组处理-array-utilities) | 数组操作工具 | 9 | | [date](#-日期处理-date-utilities) | 日期日历生成 | 1 | | [down](#-文件下载-down-utilities) | 文件下载 | 2 | | [object](#-对象处理-object-utilities) | 对象操作 | 7 | | [storage](#-存储操作-storage-utilities) | 本地存储 | 7 | | [string](#-字符串处理-string-utilities) | 字符串格式化 | 4 | | [tree](#-树形结构-tree-utilities) | 树结构操作 | 8 | | [upload](#-文件上传-upload-utilities) | 大文件上传 | 1 | | [utools](#-通用工具-utools) | 防抖节流等 | 7 | | [uuid](#-uuid生成-uuid-utilities) | ID生成 | 2 | | [watermark](#-水印工具-watermark) | 页面水印 | 1 | --- ## 🔍 类型判断 (Type Utilities) 强大的类型检测和判断工具。 ```typescript import { getTypeof, isArray, isBoolean, isString, isNumber, isObject, isFunction, } from "iota-utils"; // 获取精确类型名称 getTypeof([]); // 'array' getTypeof({}); // 'object' getTypeof(""); // 'string' getTypeof(42); // 'number' getTypeof(true); // 'boolean' getTypeof(() => {}); // 'function' getTypeof(null); // 'null' // 类型守卫函数 if (isArray(value)) { value.forEach((item) => console.log(item)); } ``` --- ## 💾 存储操作 (Storage Utilities) 完整的浏览器存储解决方案,支持 localStorage 和 sessionStorage 的操作与监听。 ```typescript import { setLocalStorage, getLocalStorage, removeLocalStorage, removeLocalStorageKey, clearLocalStorage, setSessionStorage, getSessionStorage, removeSessionStorage, removeSessionStorageKey, clearSessionStorage, monitorStorage, } from "iota-utils"; // LocalStorage 操作 setLocalStorage("user", { id: 1, name: "John" }); // 存储数据(自动序列化对象) const user = getLocalStorage("user"); // 获取数据(自动解析 JSON) removeLocalStorage("user"); // 删除单个 key(removeLocalStorageKey 的别名) removeLocalStorageKey("key1", "key2", "key3"); // 批量删除多个 key clearLocalStorage(); // 清空所有 localStorage // SessionStorage 操作 setSessionStorage("token", "abc123"); // 存储会话数据 const token = getSessionStorage("token"); // 获取会话数据 removeSessionStorage("token"); // 删除单个 key(removeSessionStorageKey 的别名) removeSessionStorageKey("key1", "key2"); // 批量删除 clearSessionStorage(); // 清空所有 sessionStorage // 监听存储变化 const cleanup = monitorStorage({ type: "both" }); // 监听 local 和 session window.addEventListener("local", (e) => { console.log("LocalStorage changed:", e.key, e.newValue); }); window.addEventListener("session", (e) => { console.log("SessionStorage changed:", e.key, e.newValue); }); cleanup(); // 停止监听 ``` --- ## 📁 文件下载 (Down Utilities) 文件下载的便捷解决方案。 ```typescript import { downFile, downStream } from "iota-utils"; // 下载文本文件 downFile("Hello, World!", "greeting.txt"); // 下载 JSON 数据 downFile(JSON.stringify({ name: "test" }), "data.json", "application/json"); // 远程文件流下载 downStream("https://api.example.com/file.pdf", "document.pdf", token, { id: 123 }); ``` --- ## 📊 数组处理 (Array Utilities) 高效的数组操作和转换工具。 ```typescript import { arrChunk, uniqueBy, removeNullish, findByKey, filterByKeys, groupBy, sortBy, arrToMap, diffArray, } from "iota-utils"; const users = [ { id: 1, name: "John", department: "IT" }, { id: 2, name: "Jane", department: "HR" }, { id: 1, name: "John", department: "IT" }, ]; // 数组分块 - 将数组按指定大小分割成多个子数组 arrChunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]] arrChunk([1, 2, 3], 2, { fillRemaining: true, fillValue: 0 }); // [[1, 2], [3, 0]] // 去重 - 根据指定键去重,返回新数组 uniqueBy(users, "id"); // [{ id: 1, name: "John", department: "IT" }, { id: 2, name: "Jane", department: "HR" }] // 移除 null/undefined - 保留 0, "", false 等假值 removeNullish([0, null, undefined, "", false]); // [0, "", false] // 按键查找 - 在数组中查找指定键值的第一个元素 findByKey(users, 2); // { id: 2, name: "Jane", department: "HR" } findByKey(users, "John", "name"); // { id: 1, name: "John", department: "IT" } // 按键数组过滤 - 保留指定键值的元素 filterByKeys(users, [1, 3]); // [{ id: 1, name: "John", department: "IT" }] // 分组 - 根据指定键分组,返回对象 groupBy(users, "department"); // { IT: [{ id: 1, name: "John" }], HR: [{ id: 2, name: "Jane" }] } // 排序 - 根据指定键排序 sortBy(users, "asc", "id"); // [{ id: 1, name: "John" }, { id: 2, name: "Jane" }] // 转 Map - 将数组转为以指定键为 key 的 Map arrToMap(users, "id"); // Map { 1 => { id: 1, name: "John" }, 2 => { id: 2, name: "Jane" } } // 差集 - 返回在第一个数组中但不在第二个数组中的元素 diffArray(users, [{ id: 1, name: "John" }]); // [{ id: 2, name: "Jane", department: "HR" }, { id: 1, name: "John", department: "IT" }] ``` --- ## 🏗️ 对象处理 (Object Utilities) 实用的对象操作工具,支持深度操作和安全访问。 ```typescript import { flattenObject, restoreObject, pick, omit, merge, getNestedValue, isEmpty, } from "iota-utils"; // 深度扁平化 - 将嵌套对象转为点分隔的单层对象 flattenObject({ user: { name: "John", address: { city: "NYC" } } }); // 返回: { 'user.name': 'John', 'user.address.city': 'NYC' } // 还原扁平对象 - 将点分隔的对象还原为嵌套结构 restoreObject({ "user.name": "John", "user.age": 30 }); // 返回: { user: { name: 'John', age: 30 } } // 选取属性 - 只保留指定的属性 pick({ name: "John", age: 30, gender: "male" }, ["name", "age"]); // 返回: { name: "John", age: 30 } // 排除属性 - 删除指定的属性 omit({ name: "John", age: 30, gender: "male" }, ["gender"]); // 返回: { name: "John", age: 30 } // 深度合并 - 递归合并多个对象,后面对象覆盖前面的 merge({ a: { x: 1, y: 10 } }, { a: { y: 2 } }, { b: 3 }); // 返回: { a: { x: 1, y: 2 }, b: 3 } // 安全获取嵌套值 - 避免空指针异常 getNestedValue({ a: { b: { c: 1 } } }, "a.b.c"); // 返回: 1 getNestedValue({ a: { b: 1 } }, "a.c", "default"); // 返回: "default" getNestedValue(null, "a.b", undefined); // 返回: undefined // 判断空对象/数组 - 支持对象和数组 isEmpty({}); // 返回: true isEmpty([]); // 返回: true isEmpty({ a: 1 }); // 返回: false isEmpty([1]); // 返回: false isEmpty(null); // 返回: true isEmpty(undefined); // 返回: true ``` --- ## 🧵 字符串处理 (String Utilities) 字符串格式化和模板处理。 ```typescript import { formatStr, templateReplace, decodeParams, encodeParams } from "iota-utils"; // 字符串替换 formatStr("Hello %u", "World"); // "Hello World" // 模板替换 templateReplace("Hello ((name)), age is ((age))", { name: "John", age: 30 }); // "Hello John, age is 30" // URL 参数解析 decodeParams("name=John&age=30"); // { name: "John", age: "30" } // 对象转 URL 参数 encodeParams({ name: "John", age: 30 }); // "?name=John&age=30" ``` --- ## 🌳 树形结构 (Tree Utilities) 完整的树形数据结构操作工具集,支持树与扁平结构互转、节点查找、搜索和删除。 ```typescript import { toFlatTree, toTreeFlat, deepClone, deleteTreeNode, findTreeNode, fuzzySearchTree, searchTree, } from "iota-utils"; const tree = [ { id: "1", title: "Root", children: [ { id: "1-1", title: "Child 1", children: [{ id: "1-1-1", title: "Grandchild" }] }, { id: "1-2", title: "Child 2" }, ], }, ]; // 树转扁平 - 将树形结构展开为一维数组 toFlatTree(tree); // 返回: [{ id: "1", title: "Root" }, { id: "1-1", title: "Child 1" }, { id: "1-1-1", title: "Grandchild" }, { id: "1-2", title: "Child 2" }] // 扁平转树 - 将一维数组还原为树形结构 const flatList = [ { id: "1", pid: null, title: "Root" }, { id: "1-1", pid: "1", title: "Child" }, ]; toTreeFlat(flatList, null); // 第二个参数为根节点 pid // 深拷贝 - 递归深拷贝对象或数组 deepClone(tree); // 返回与原对象完全独立的新对象 // 删除节点 - 根据 id 删除指定节点及其子节点 deleteTreeNode(tree, "1-1"); // 返回: [{ id: "1", title: "Root", children: [{ id: "1-2", title: "Child 2" }] }] // 查找节点 - 查找并返回匹配的第一个节点 findTreeNode(tree, "1-1"); // 返回: { id: "1-1", title: "Child 1", children: [...] } // 模糊搜索树 - 【返回树结构】保留父子关系,过滤匹配的分支 // 特点:保留树形层级结构,匹配节点及其祖先会被保留 fuzzySearchTree(tree, "Child"); // 返回: [{ id: "1", title: "Root", children: [{ id: "1-1", title: "Child 1" }, { id: "1-2", title: "Child 2" }] }] // 精确搜索 - 【返回平铺数组】只返回匹配的节点,不保留层级 // 特点:返回扁平化的节点数组,每个节点包含 fullPath 字段表示完整路径 searchTree(tree, "Child", { nameKey: "title" }); // 返回: [{ id: "1-1", title: "Child 1", fullPath: "Root/Child 1" }, { id: "1-2", title: "Child 2", fullPath: "Root/Child 2" }] ``` ### 🔍 搜索函数差异对比 | 函数 | 返回类型 | 保留层级 | 适用场景 | | ----------------- | ---------------------------------------- | -------- | ------------------------------------------ | | `fuzzySearchTree` | 树结构 `T[]` | ✅ 是 | 用于展示树结构的搜索过滤,如树组件搜索 | | `searchTree` | 平铺数组 `(T & { fullPath?: string })[]` | ❌ 否 | 用于获取匹配节点的列表,如搜索结果列表展示 | **设计差异说明:** - **`fuzzySearchTree`**:保留树形结构,匹配节点的祖先节点也会被保留,适合需要展示完整层级关系的场景(如树形菜单搜索) - **`searchTree`**:返回平铺的节点数组,每个节点附带 `fullPath` 属性表示从根节点到该节点的路径,适合需要展示搜索结果列表的场景(如全局搜索) --- ## ⚡ 异步处理 (Async Utilities) Go 风格的错误处理。 ```typescript import { catchError, wrapCatch } from "iota-utils"; // 直接错误捕获 const [err, data] = await catchError(async () => { const response = await fetch("/api/data"); return response.json(); }); if (err) { console.error("Error:", err); return; } console.log(data); // 包装函数 const safeFetch = wrapCatch(fetch); const [err2, result] = await safeFetch("/api/data"); ``` --- ## ⬆️ 文件上传 (Upload Utilities) 大文件切片上传。 ```typescript import { uploadSlice } from "iota-utils"; const file = document.querySelector('input[type="file"]').files[0]; const result = await uploadSlice( file, 1024 * 1024, // 1MB 分片大小 "/api/upload", // 上传地址 (progress) => console.log(`Progress: ${progress.toFixed(1)}%`), { headers: { Authorization: `Bearer ${token}` } }, ); if (result.finish) { console.log("Upload completed!"); } else { console.log("Failed slices:", result.failedSlices); } ``` --- ## 🛠️ 通用工具 (Utools) 常用工具函数。 ```typescript import { debounce, throttle, copyText, sleep } from "iota-utils"; // 防抖 const debouncedSearch = debounce((query: string) => { console.log("Searching:", query); }, 300); // 节流 const throttledScroll = throttle(() => { console.log("Scrolling"); }, 100); // 复制到剪贴板 await copyText("Hello!"); // 延时 await sleep(1000); console.log("1 second later..."); ``` --- ## 🆔 UUID 生成 (UUID Utilities) 唯一标识符生成。 ```typescript import { generateUUID, generateString } from "iota-utils"; // 标准 UUID v4 generateUUID(); // "550e8400-e29b-41d4-a716-446655440000" // 自定义模板 generateUUID("xxxx-xxxx"); // "a1b2-c3d4" // 随机字符串(字母开头) generateString(); // 默认 8 位: "Ak7x9Pq2" generateString(16); // 自定义长度: "Bw3mK9nX5vY2pQ8r" ``` --- ## 📅 日期处理 (Date Utilities) 日历生成工具。 ```typescript import { generateCalendar } from "iota-utils"; interface CalendarDay { date: Date; meta: { year: number; month: number; day: number; dayOfWeek: string; type: "prev" | "current" | "next"; formattedDate: string; }; } const calendar: CalendarDay[] = generateCalendar(2024, 3); calendar.forEach((day) => { if (day.meta.type === "current") { console.log(`${day.meta.formattedDate}: ${day.meta.dayOfWeek}`); } }); ``` --- ## 🎨 水印工具 (Watermark) 页面水印解决方案。 ```typescript import { watermark } from "iota-utils"; // 设置全屏水印 watermark.set("机密文件"); // 自定义样式 watermark.setOptions({ width: 400, height: 200, fontSize: 18, color: "rgba(255, 0, 0, 0.15)", rotate: -30, }); // 指定容器 watermark.set("内部文档", containerElement); // 清除水印 watermark.clear(); ``` --- ## 类型定义 ```typescript // 存储变化事件 interface StorageChangeEvent extends Event { key: string; newValue: string; oldValue: string | null; storageArea: "local" | "session"; } // 水印配置 interface WatermarkOptions { width?: number; height?: number; fontSize?: number; fontFamily?: string; color?: string; rotate?: number; zIndex?: number; } // 错误结果 type ErrorResult = [Error | null, T | undefined]; ``` --- ## 浏览器兼容性 - Chrome 60+ - Firefox 55+ - Safari 12+ - Edge 79+ ## 相关项目 ### iota-react-admin - React 后台管理系统模版 **项目地址**: [https://github.com/iotaoo/iota-react-admin](https://github.com/iotaoo/iota-react-admin) ### iota-fetch - Axios 二次封装 **项目地址**: [https://github.com/iotaoo/iota-fetch](https://github.com/iotaoo/iota-fetch) --- ## 许可证 MIT License - 详见 [LICENSE](LICENSE) 文件 ## 贡献 欢迎提交 Issue 和 Pull Request! 1. 所有测试通过:`npm test` 2. 代码格式化:`npm run lint` 3. 类型检查:`npm run type-check`