dengzy-js-utils
v1.0.7
Published
包含常用数学运算和数据处理工具函数
Readme
MathUtils : object
包含常用数学运算和数据处理工具函数
函数目录
- timeExecution - 测量函数执行时间
- safeJsonParse - 安全解析JSON字符串
- deepObjectDiff - 深度比较两个对象
- transposeMatrix - 转置二维数组
- binarySearchIndex - 二分查找
- debounceLeading - 领先边缘防抖
- parseJsonp - 解析JSONP字符串
- deepCloneCircular - 深度克隆对象
- escapeRegex - 转义正则表达式
- flattenObject - 扁平化嵌套对象
- unflattenObject - 展开扁平对象
- uniqueDeep - 深度去重数组
- timeSince - 计算人性化时间差
- formatBytes - 格式化字节数
- convertBase - 进制转换
- parseQueryString - 解析查询字符串
- runAsyncSequence - 顺序执行异步任务
- padObjectKeys - 键名添加前后缀
- groupByPath - 按路径分组对象
- toSafePropertyName - 生成安全属性名
Kind: global namespace
- MathUtils : object
- .timeExecution(fn, [...args]) ⇒ Promise.<{result: any, time: number}>
- .safeJsonParse(jsonString, [fallback]) ⇒ any
- .deepObjectDiff(obj1, obj2) ⇒ object
- .transposeMatrix(matrix) ⇒ Array.<Array.<any>>
- .binarySearchIndex(arr, value, [compareFn]) ⇒ number
- .debounceLeading(fn, wait) ⇒ function
- .parseJsonp(jsonp, [callbackName]) ⇒ object
- .deepCloneCircular(obj) ⇒ object
- .escapeRegex(str) ⇒ string
- .flattenObject(obj, [separator]) ⇒ object
- .unflattenObject(obj, [separator]) ⇒ object
- .uniqueDeep(arr) ⇒ Array.<any>
- .timeSince(date) ⇒ string
- .formatBytes(bytes, [decimals]) ⇒ string
- .convertBase(numStr, fromBase, toBase) ⇒ string
- .parseQueryString(queryString) ⇒ object
- .runAsyncSequence(tasks) ⇒ Promise.<Array.<any>>
- .padObjectKeys(obj, [prefix], [suffix]) ⇒ object
- .groupByPath(arr, path) ⇒ object
- .toSafePropertyName(str) ⇒ string
MathUtils.timeExecution(fn, [...args]) ⇒ Promise.<{result: any, time: number}>
测量函数(同步或异步)的执行时间
Kind: static method of MathUtils
Returns: Promise.<{result: any, time: number}> - 包含执行结果和耗时(毫秒)的Promise对象
| Param | Type | Description | | --- | --- | --- | | fn | function | 待执行的目标函数 | | [...args] | any | 传递给目标函数的参数列表 |
Example
// 异步示例
const { result, time } = await timeExecution(async () => {
await new Promise(resolve => setTimeout(resolve, 1000));
return 'done';
});
console.log(`执行结果: ${result}, 耗时: ${time}ms`);MathUtils.safeJsonParse(jsonString, [fallback]) ⇒ any
安全解析JSON字符串,解析失败时返回回退值
Kind: static method of MathUtils
Returns: any - 解析后的对象或回退值
| Param | Type | Default | Description | | --- | --- | --- | --- | | jsonString | string | | 待解析的JSON格式字符串 | | [fallback] | any | | 解析失败时的回退值(默认值:null) |
Example
const data = safeJsonParse('{invalid json}', {}); // 返回空对象{}MathUtils.deepObjectDiff(obj1, obj2) ⇒ object
深度比较两个对象并返回差异
Kind: static method of MathUtils
Returns: object - 差异对象,包含added(新增)、removed(删除)、changed(修改)属性
| Param | Type | Description | | --- | --- | --- | | obj1 | object | 待比较的第一个对象 | | obj2 | object | 待比较的第二个对象 |
Example
const diff = deepObjectDiff({ a: 1, b: 2 }, { a: 1, b: 3, c: 4 });
// { added: { c: 4 }, removed: {}, changed: { b: { from: 2, to: 3 } } }MathUtils.transposeMatrix(matrix) ⇒ Array.<Array.<any>>
转置二维数组(矩阵)
Kind: static method of MathUtils
Returns: Array.<Array.<any>> - 转置后的矩阵
| Param | Type | Description | | --- | --- | --- | | matrix | Array.<Array.<any>> | 待转置的矩阵(二维数组) |
Example
transposeMatrix([[1, 2], [3, 4]]); // 返回 [[1, 3], [2, 4]]MathUtils.binarySearchIndex(arr, value, [compareFn]) ⇒ number
在有序数组中执行二分查找
Kind: static method of MathUtils
Returns: number - 找到值的索引或插入位置(未找到时)
| Param | Type | Description | | --- | --- | --- | | arr | Array.<any> | 有序数组(升序排列) | | value | any | 待搜索的值 | | [compareFn] | function | 自定义比较函数(默认使用数值/字符串比较) |
Example
binarySearchIndex([1, 3, 5, 7], 4); // 返回 2(插入位置)MathUtils.debounceLeading(fn, wait) ⇒ function
返回立即执行的防抖函数(领先边缘触发)
Kind: static method of MathUtils
Returns: function - 防抖处理后的函数
| Param | Type | Description | | --- | --- | --- | | fn | function | 待防抖的目标函数 | | wait | number | 防抖时间间隔(毫秒) |
Example
const handleClick = debounceLeading(() => console.log('点击触发'), 500);
button.addEventListener('click', handleClick);MathUtils.parseJsonp(jsonp, [callbackName]) ⇒ object
将JSONP字符串解析为JavaScript对象
Kind: static method of MathUtils
Returns: object - 解析后的JSON对象
| Param | Type | Description |
| --- | --- | --- |
| jsonp | string | JSONP格式字符串(如:callback({...})) |
| [callbackName] | string | 可选的回调函数名校验(默认不校验) |
Example
parseJsonp('dataCallback({ "key": "value" })', 'dataCallback');MathUtils.deepCloneCircular(obj) ⇒ object
深度克隆对象(支持循环引用)
Kind: static method of MathUtils
Returns: object - 深度克隆后的对象(保留循环引用)
| Param | Type | Description | | --- | --- | --- | | obj | object | 待克隆的对象(支持数组/对象/循环引用) |
Example
const obj = { a: 1 }; obj.self = obj;
const clone = deepCloneCircular(obj);
console.log(clone.self === clone); // trueMathUtils.escapeRegex(str) ⇒ string
转义字符串中的正则表达式特殊字符
Kind: static method of MathUtils
Returns: string - 转义后的安全字符串(特殊字符前加反斜杠)
| Param | Type | Description | | --- | --- | --- | | str | string | 待转义的字符串 |
Example
escapeRegex('a.b'); // 返回 'a\\.b'MathUtils.flattenObject(obj, [separator]) ⇒ object
将嵌套对象扁平化为点分隔键的单层对象
Kind: static method of MathUtils
Returns: object - 扁平化后的单层对象
| Param | Type | Default | Description | | --- | --- | --- | --- | | obj | object | | 待扁平化的嵌套对象 | | [separator] | string | "'.'" | 键路径分隔符(默认:点号) |
Example
flattenObject({ a: { b: 2 }, c: 3 }, '_'); // { 'a_b': 2, c: 3 }MathUtils.unflattenObject(obj, [separator]) ⇒ object
将扁平对象转换为嵌套对象
Kind: static method of MathUtils
Returns: object - 转换后的嵌套对象
| Param | Type | Default | Description | | --- | --- | --- | --- | | obj | object | | 点分隔键的扁平对象 | | [separator] | string | "'.'" | 键路径分隔符(默认:点号) |
Example
unflattenObject({ 'a_b': 2, c: 3 }, '_'); // { a: { b: 2 }, c: 3 }MathUtils.uniqueDeep(arr) ⇒ Array.<any>
按深度相等性移除数组中的重复对象
Kind: static method of MathUtils
Returns: Array.<any> - 去重后的唯一对象数组
| Param | Type | Description | | --- | --- | --- | | arr | Array.<any> | 待去重的数组(包含对象) |
Example
uniqueDeep([{ a: 1 }, { a: 1 }, { a: 2 }]); // 返回 [{ a: 1 }, { a: 2 }]MathUtils.timeSince(date) ⇒ string
计算从给定时间到现在的人性化时间差
Kind: static method of MathUtils
Returns: string - 人性化时间差字符串(如:"3分钟前")
| Param | Type | Description | | --- | --- | --- | | date | Date | number | 过去的日期对象或时间戳 |
Example
timeSince(new Date('2023-01-01')); // "2年前提"(假设当前时间为2025年)MathUtils.formatBytes(bytes, [decimals]) ⇒ string
将字节数格式化为可读性字符串
Kind: static method of MathUtils
Returns: string - 格式化后的字符串(如:"1.50 MB")
| Param | Type | Default | Description | | --- | --- | --- | --- | | bytes | number | | 字节数值 | | [decimals] | number | 2 | 保留的小数位数(默认:2位) |
Example
formatBytes(1048576, 1); // "1.0 MB"MathUtils.convertBase(numStr, fromBase, toBase) ⇒ string
数字字符串进制转换
Kind: static method of MathUtils
Returns: string - 转换后的目标进制数字字符串
| Param | Type | Description | | --- | --- | --- | | numStr | string | 原始进制的数字字符串 | | fromBase | number | 原始进制(2-36) | | toBase | number | 目标进制(2-36) |
Example
convertBase('FF', 16, 2); // "11111111"(十六进制转二进制)MathUtils.parseQueryString(queryString) ⇒ object
解析URL查询字符串为对象
Kind: static method of MathUtils
Returns: object - 解析后的键值对对象(自动解码URI)
| Param | Type | Description | | --- | --- | --- | | queryString | string | 查询字符串(支持带前导问号) |
Example
parseQueryString('?name=John&age=25'); // { name: 'John', age: '25' }MathUtils.runAsyncSequence(tasks) ⇒ Promise.<Array.<any>>
按顺序执行异步任务数组
Kind: static method of MathUtils
Returns: Promise.<Array.<any>> - 按执行顺序排列的结果数组
| Param | Type | Description | | --- | --- | --- | | tasks | Array.<function()> | 异步任务数组(每个任务返回Promise) |
Example
await runAsyncSequence([
() => Promise.resolve(1),
() => Promise.resolve(2)
]); // [1, 2]MathUtils.padObjectKeys(obj, [prefix], [suffix]) ⇒ object
为对象键添加前缀和后缀
Kind: static method of MathUtils
Returns: object - 新对象(所有键添加前后缀)
| Param | Type | Default | Description | | --- | --- | --- | --- | | obj | object | | 源对象 | | [prefix] | string | "''" | 键前缀(默认:空字符串) | | [suffix] | string | "''" | 键后缀(默认:空字符串) |
Example
padObjectKeys({ id: 1 }, 'item_', '_data'); // { 'item_id_data': 1 }MathUtils.groupByPath(arr, path) ⇒ object
按嵌套属性路径对对象数组分组
Kind: static method of MathUtils
Returns: object - 分组结果(键为路径值,值为对象数组)
| Param | Type | Description | | --- | --- | --- | | arr | Array.<object> | 对象数组 | | path | string | 分组属性路径(点分隔,如"a.b.c") |
Example
groupByPath([{ cat: { id: 1 } }, { cat: { id: 2 } }], 'cat.id');
// { '1': [{ cat: { id: 1 } }], '2': [{ cat: { id: 2 } }] }MathUtils.toSafePropertyName(str) ⇒ string
转换为安全的JavaScript属性名
Kind: static method of MathUtils
Returns: string - 安全属性名(仅包含字母/数字/下划线,以字母或下划线开头)
| Param | Type | Description | | --- | --- | --- | | str | string | 原始字符串 |
Example
toSafePropertyName('-invalid-name 123'); // '_invalid_name_123'