sh-tools 2.3.9 → 2.3.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +159 -26
- package/package.json +2 -2
- package/packages/expr/index.js +458 -450
- package/packages/index.js +19 -0
- package/packages/utils/number.js +0 -10
- package/packages/utils/string.js +20 -4
package/README.md
CHANGED
|
@@ -1,39 +1,172 @@
|
|
|
1
1
|
# sh-tools
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
{**以下是 Gitee 平台说明,您可以替换此简介**
|
|
5
|
-
Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台
|
|
6
|
-
无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)}
|
|
3
|
+
## 概述
|
|
7
4
|
|
|
8
|
-
|
|
9
|
-
软件架构说明
|
|
5
|
+
SH-Tools 提供了一个强大的表达式求值器模块,支持复杂的数学运算、逻辑判断、函数调用和模板字符串解析。特别适合动态计算、规则引擎和配置化计算场景。
|
|
10
6
|
|
|
7
|
+
## 安装
|
|
8
|
+
npm install sh-tools
|
|
11
9
|
|
|
12
|
-
|
|
10
|
+
## 引入方式
|
|
11
|
+
import { utils, expr } from 'sh-tools'
|
|
13
12
|
|
|
14
|
-
1. xxxx
|
|
15
|
-
2. xxxx
|
|
16
|
-
3. xxxx
|
|
17
13
|
|
|
18
|
-
|
|
14
|
+
## 核心 API
|
|
15
|
+
| 函数名 | 参数 | 返回值 | 描述 | 示例 |
|
|
16
|
+
|--------|------|--------|------|------|
|
|
17
|
+
| `utils.calculate(expression, data?)` | `expression: string` - 表达式字符串<br>`data?: object` - 数据上下文 | `any` - 计算结果 | 计算表达式并返回结果,支持 `{}` 模板 | `utils.calculate("1+2*3")` → `7`<br>`utils.calculate("用户{name}", {name:"张三"})` → `"用户张三"` |
|
|
18
|
+
| `utils.calculateLog(expression, data?)` | `expression: string`<br>`data?: object` | `{result, log, treeLog}` - 结果和日志 | 计算表达式并返回详细执行日志 | `utils.calculateLog("sum([1,2,3])")` → `{result: 6, log: [...], treeLog: [...]}` |
|
|
19
|
+
| `expr.registerFunction(name, fn, override?)` | `name: string\|object` - 函数名或对象<br>`fn: Function` - 函数实现<br>`override?: boolean` - 是否覆盖 | `void` | 注册自定义函数 | `expr.registerFunction('double', x=>x*2)`<br>`expr.registerFunction({square: x=>x*x})` |
|
|
20
|
+
| `expr.extendOperator(symbol, config, override?)` | `symbol: string` - 运算符<br>`config: object` - 配置<br>`override?: boolean` - 是否覆盖 | `void` | 扩展自定义运算符 | `expr.extendOperator('//', {precedence:11, fn:(a,b)=>Math.floor(a/b)})` |
|
|
19
21
|
|
|
20
|
-
1. xxxx
|
|
21
|
-
2. xxxx
|
|
22
|
-
3. xxxx
|
|
23
22
|
|
|
24
|
-
|
|
23
|
+
# 内置函数
|
|
25
24
|
|
|
26
|
-
|
|
27
|
-
2. 新建 Feat_xxx 分支
|
|
28
|
-
3. 提交代码
|
|
29
|
-
4. 新建 Pull Request
|
|
25
|
+
## 数学函数
|
|
30
26
|
|
|
27
|
+
| 函数名 | 参数 | 返回值 | 描述 | 示例 |
|
|
28
|
+
|--------|------|--------|------|------|
|
|
29
|
+
| `abs` | `x: number` | `number` | 绝对值 | `abs(-10)` → `10` |
|
|
30
|
+
| `ceil` | `x: number` | `number` | 向上取整 | `ceil(3.14)` → `4` |
|
|
31
|
+
| `floor` | `x: number` | `number` | 向下取整 | `floor(3.14)` → `3` |
|
|
32
|
+
| `round` | `x: number` | `number` | 四舍五入 | `round(3.14)` → `3` |
|
|
33
|
+
| `pow` | `base: number, exponent: number` | `number` | 幂运算 | `pow(2, 3)` → `8` |
|
|
34
|
+
| `sqrt` | `x: number` | `number` | 平方根 | `sqrt(9)` → `3` |
|
|
35
|
+
| `sin` | `x: number` | `number` | 正弦 | `sin(0)` → `0` |
|
|
36
|
+
| `cos` | `x: number` | `number` | 余弦 | `cos(0)` → `1` |
|
|
37
|
+
| `tan` | `x: number` | `number` | 正切 | `tan(0)` → `0` |
|
|
38
|
+
| `log` | `x: number` | `number` | 自然对数 | `log(10)` → `2.302...` |
|
|
39
|
+
| `exp` | `x: number` | `number` | e的幂次 | `exp(1)` → `2.718...` |
|
|
40
|
+
| `random` | `min?: number, max?: number` | `number` | 随机数 | `random()` → `0.123`<br>`random(1,10)` → `5` |
|
|
41
|
+
| `min` | `...args: number[]` 或 `arr: number[]` | `number` | 最小值 | `min(5,2,8,1)` → `1`<br>`min([5,2,8,1])` → `1` |
|
|
42
|
+
| `max` | `...args: number[]` 或 `arr: number[]` | `number` | 最大值 | `max(5,2,8,1)` → `8`<br>`max([5,2,8,1])` → `8` |
|
|
43
|
+
| `add` | `a: number, b: number` | `number` | 加法(精确) | `add(0.1, 0.2)` → `0.3` |
|
|
44
|
+
| `subtract` | `a: number, b: number` | `number` | 减法(精确) | `subtract(0.3, 0.1)` → `0.2` |
|
|
45
|
+
| `multiply` | `a: number, b: number` | `number` | 乘法(精确) | `multiply(0.1, 0.2)` → `0.02` |
|
|
46
|
+
| `divide` | `a: number, b: number` | `number` | 除法(精确) | `divide(0.3, 0.1)` → `3` |
|
|
47
|
+
| `toFixed` | `value: number, digits: number` | `string` | 保留小数位 | `toFixed(3.14159, 2)` → `"3.14"` |
|
|
48
|
+
| `toInteger` | `value: any` | `number` | 转整数 | `toInteger("123")` → `123`<br>`toInteger(3.14)` → `3` |
|
|
49
|
+
| `toNumber` | `value: any` | `number` | 转数字 | `toNumber("3.14")` → `3.14`<br>`toNumber("123")` → `123` |
|
|
50
|
+
| `truncate` | `value: number, digits: number` | `number` | 截断小数位 | `truncate(3.14159, 2)` → `3.14` |
|
|
31
51
|
|
|
32
|
-
|
|
52
|
+
## 数组函数
|
|
53
|
+
|
|
54
|
+
| 函数名 | 参数 | 返回值 | 描述 | 示例 |
|
|
55
|
+
|--------|------|--------|------|------|
|
|
56
|
+
| `sum` | `arr: number[]` | `number` | 求和 | `sum([1,2,3])` → `6` |
|
|
57
|
+
| `mean` | `arr: number[]` | `number` | 平均值 | `mean([1,2,3,4])` → `2.5` |
|
|
58
|
+
| `min` | `arr: number[]` | `number` | 最小值 | `min([5,2,8,1])` → `1` |
|
|
59
|
+
| `max` | `arr: number[]` | `number` | 最大值 | `max([5,2,8,1])` → `8` |
|
|
60
|
+
| `flatten` | `arr: any[]` | `any[]` | 扁平化数组 | `flatten([[1,2],[3,4]])` → `[1,2,3,4]` |
|
|
61
|
+
| `uniq` | `arr: any[]` | `any[]` | 数组去重 | `uniq([1,2,2,3,3,3])` → `[1,2,3]` |
|
|
62
|
+
| `includes` | `arr: any[], value: any` | `boolean` | 包含判断 | `includes([1,2,3], 2)` → `true` |
|
|
63
|
+
| `first` | `arr: any[]` | `any` | 第一个元素 | `first([1,2,3])` → `1` |
|
|
64
|
+
| `last` | `arr: any[]` | `any` | 最后一个元素 | `last([1,2,3])` → `3` |
|
|
65
|
+
| `length` | `arr: any[]` | `number` | 数组长度 | `length([1,2,3,4,5])` → `5` |
|
|
66
|
+
| `slice` | `arr: any[], start: number, end?: number` | `any[]` | 切片 | `slice([1,2,3,4,5], 1, 3)` → `[2,3]` |
|
|
67
|
+
| `indexOf` | `arr: any[], value: any, fromIndex?: number` | `number` | 查找索引 | `indexOf([1,2,3,2], 2)` → `1` |
|
|
68
|
+
| `union` | `...arrays: any[][]` | `any[]` | 数组合并并去重 | `union([1,2], [2,3], [3,4])` → `[1,2,3,4]` |
|
|
69
|
+
| `pluck` | `arr: object[], property: string` | `any[]` | 提取属性值 | `pluck([{id:1},{id:2},{id:3}], 'id')` → `[1,2,3]` |
|
|
70
|
+
| `orderBy` | `arr: any[], field: string, order?: 'asc'\|'desc'` | `any[]` | 排序 | `orderBy([{age:30},{age:25}], 'age', 'asc')` → `[{age:25},{age:30}]` |
|
|
71
|
+
| `groupBy` | `arr: any[], field: string` | `object` | 分组 | `groupBy([{type:'A'},{type:'B'},{type:'A'}], 'type')` → `{A:[...], B:[...]}` |
|
|
72
|
+
| `countBy` | `arr: any[], field: string` | `object` | 统计计数 | `countBy([{type:'A'},{type:'B'},{type:'A'}], 'type')` → `{A:2, B:1}` |
|
|
73
|
+
| `toArrayTree` | `arr: any[], options?: object` | `any[]` | 转树形结构 | `toArrayTree([{id:1,pid:0},{id:2,pid:1}])` → `[{id:1,children:[{id:2}]}]` |
|
|
74
|
+
| `toTreeArray` | `tree: any[], options?: object` | `any[]` | 树形转数组 | `toTreeArray([{id:1,children:[{id:2}]}])` → `[{id:1,pid:0},{id:2,pid:1}]` |
|
|
75
|
+
| `invoke` | `arr: any[], methodName: string, ...args: any[]` | `any[]` | 调用方法 | `invoke([[1,2],[3,4]], 'join', ',')` → `['1,2','3,4']` |
|
|
76
|
+
| `unzip` | `arr: any[][]` | `any[][]` | 解压数组 | `unzip([[1,'a'],[2,'b'],[3,'c']])` → `[[1,2,3],['a','b','c']]` |
|
|
77
|
+
| `includeArrays` | `arr1: any[], arr2: any[]` | `boolean` | 数组包含 | `includeArrays([1,2,3,4], [2,3])` → `true` |
|
|
78
|
+
|
|
79
|
+
## 字符串函数
|
|
80
|
+
|
|
81
|
+
| 函数名 | 参数 | 返回值 | 描述 | 示例 |
|
|
82
|
+
|--------|------|--------|------|------|
|
|
83
|
+
| `trim` | `str: string` | `string` | 去除两端空格 | `trim(' hello ')` → `'hello'` |
|
|
84
|
+
| `trimLeft` | `str: string` | `string` | 去除左侧空格 | `trimLeft(' hello')` → `'hello'` |
|
|
85
|
+
| `trimRight` | `str: string` | `string` | 去除右侧空格 | `trimRight('hello ')` → `'hello'` |
|
|
86
|
+
| `camelCase` | `str: string` | `string` | 转驼峰命名 | `camelCase('hello_world')` → `'helloWorld'`<br>`camelCase('hello-world')` → `'helloWorld'` |
|
|
87
|
+
| `kebabCase` | `str: string` | `string` | 转烤串命名 | `kebabCase('helloWorld')` → `'hello-world'`<br>`kebabCase('HelloWorld')` → `'hello-world'` |
|
|
88
|
+
| `startsWith` | `str: string, search: string` | `boolean` | 是否以指定字符串开头 | `startsWith('hello', 'he')` → `true`<br>`startsWith('hello', 'lo')` → `false` |
|
|
89
|
+
| `endsWith` | `str: string, search: string` | `boolean` | 是否以指定字符串结尾 | `endsWith('hello', 'lo')` → `true`<br>`endsWith('hello', 'he')` → `false` |
|
|
90
|
+
| `toValueString` | `value: any` | `string` | 转值字符串 | `toValueString(123)` → `'123'`<br>`toValueString(null)` → `''` |
|
|
91
|
+
| `toNumberString` | `value: any, digits?: number` | `string` | 转数字字符串 | `toNumberString(3.14159, 2)` → `'3.14'` |
|
|
92
|
+
|
|
93
|
+
## 日期函数
|
|
94
|
+
|
|
95
|
+
| 函数名 | 参数 | 返回值 | 描述 | 示例 |
|
|
96
|
+
|--------|------|--------|------|------|
|
|
97
|
+
| `now` | 无 | `number` | 当前时间戳 | `now()` → `1640995200000` |
|
|
98
|
+
| `timestamp` | 无 | `number` | 当前时间戳 | `timestamp()` → `1640995200000` |
|
|
99
|
+
| `toDateString` | `date: any, format?: string` | `string` | 日期格式化 | `toDateString(1640995200000, 'YYYY-MM-DD')` → `'2022-01-01'` |
|
|
100
|
+
| `getYearDiff` | `date1: string\|number, date2: string\|number` | `number` | 年份差 | `getYearDiff('2020-01-01', '2024-01-01')` → `4` |
|
|
101
|
+
| `getMonthDiff` | `date1: string\|number, date2: string\|number` | `number` | 月份差 | `getMonthDiff('2024-01-01', '2024-06-01')` → `5` |
|
|
102
|
+
| `getDayDiff` | `date1: string\|number, date2: string\|number` | `number` | 天数差 | `getDayDiff('2024-01-01', '2024-01-10')` → `9` |
|
|
103
|
+
| `getHourDiff` | `time1: string\|number, time2: string\|number` | `number` | 小时差 | `getHourDiff('2024-01-01 10:00', '2024-01-01 15:30')` → `5.5` |
|
|
104
|
+
| `getMinuteDiff` | `time1: string\|number, time2: string\|number` | `number` | 分钟差 | `getMinuteDiff('10:30', '11:45')` → `75` |
|
|
105
|
+
| `getSecondDiff` | `time1: string\|number, time2: string\|number` | `number` | 秒数差 | `getSecondDiff('12:00:00', '12:01:30')` → `90` |
|
|
106
|
+
| `getDayOfMonth` | `date: string\|number` | `number` | 当月第几天 | `getDayOfMonth('2024-01-15')` → `15` |
|
|
107
|
+
|
|
108
|
+
## 对象函数
|
|
109
|
+
|
|
110
|
+
| 函数名 | 参数 | 返回值 | 描述 | 示例 |
|
|
111
|
+
|--------|------|--------|------|------|
|
|
112
|
+
| `has` | `obj: object, key: string` | `boolean` | 检查属性是否存在 | `has({name:'John'}, 'name')` → `true` |
|
|
113
|
+
| `get` | `obj: object, path: string, defaultValue?: any` | `any` | 深度获取属性值 | `get({user:{name:'John'}}, 'user.name')` → `'John'`<br>`get({}, 'user.name', '默认值')` → `'默认值'` |
|
|
114
|
+
| `assign` | `target: object, ...sources: object[]` | `object` | 对象属性分配 | `assign({}, {a:1}, {b:2})` → `{a:1,b:2}` |
|
|
115
|
+
| `merge` | `...objects: object[]` | `object` | 深度合并对象 | `merge({a:{x:1}}, {a:{y:2}, b:3})` → `{a:{x:1,y:2},b:3}` |
|
|
116
|
+
| `pick` | `obj: object, keys: string[]` | `object` | 选取指定属性 | `pick({name:'John',age:30,city:'NY'}, ['name','age'])` → `{name:'John',age:30}` |
|
|
117
|
+
| `omit` | `obj: object, keys: string[]` | `object` | 排除指定属性 | `omit({x:1,y:2,z:3}, ['z'])` → `{x:1,y:2}` |
|
|
118
|
+
|
|
119
|
+
## 类型判断函数
|
|
120
|
+
|
|
121
|
+
| 函数名 | 参数 | 返回值 | 描述 | 示例 |
|
|
122
|
+
|--------|------|--------|------|------|
|
|
123
|
+
| `isNaN` | `value: any` | `boolean` | 是否是NaN | `isNaN(NaN)` → `true`<br>`isNaN(123)` → `false` |
|
|
124
|
+
| `isArray` | `value: any` | `boolean` | 是否是数组 | `isArray([1,2,3])` → `true`<br>`isArray({})` → `false` |
|
|
125
|
+
| `isFloat` | `value: any` | `boolean` | 是否是浮点数 | `isFloat(3.14)` → `true`<br>`isFloat(3)` → `false` |
|
|
126
|
+
| `isInteger` | `value: any` | `boolean` | 是否是整数 | `isInteger(3)` → `true`<br>`isInteger(3.14)` → `false` |
|
|
127
|
+
| `isBoolean` | `value: any` | `boolean` | 是否是布尔值 | `isBoolean(true)` → `true`<br>`isBoolean('true')` → `false` |
|
|
128
|
+
| `isString` | `value: any` | `boolean` | 是否是字符串 | `isString('hello')` → `true`<br>`isString(123)` → `false` |
|
|
129
|
+
| `isNumber` | `value: any` | `boolean` | 是否是数字 | `isNumber(123)` → `true`<br>`isNumber('123')` → `false` |
|
|
130
|
+
| `isPlainObject` | `value: any` | `boolean` | 是否是纯对象 | `isPlainObject({})` → `true`<br>`isPlainObject([])` → `false` |
|
|
131
|
+
| `isDate` | `value: any` | `boolean` | 是否是日期对象 | `isDate(new Date())` → `true`<br>`isDate('2024-01-01')` → `false` |
|
|
132
|
+
| `isEmpty` | `value: any` | `boolean` | 是否为空 | `isEmpty([])` → `true`<br>`isEmpty({})` → `true`<br>`isEmpty('')` → `true`<br>`isEmpty([1])` → `false` |
|
|
133
|
+
| `isNull` | `value: any` | `boolean` | 是否是null | `isNull(null)` → `true`<br>`isNull(undefined)` → `false` |
|
|
134
|
+
| `isMatch` | `obj: object, source: object` | `boolean` | 是否部分匹配 | `isMatch({a:1,b:2,c:3}, {a:1,b:2})` → `true` |
|
|
135
|
+
| `isEqual` | `value1: any, value2: any` | `boolean` | 深度相等比较 | `isEqual({a:[1,2]}, {a:[1,2]})` → `true`<br>`isEqual({a:1}, {a:1,b:2})` → `false` |
|
|
136
|
+
| `getSize` | `value: any` | `number` | 获取大小 | `getSize([1,2,3])` → `3`<br>`getSize({a:1,b:2})` → `2`<br>`getSize('hello')` → `5` |
|
|
137
|
+
|
|
138
|
+
## 工具函数
|
|
139
|
+
|
|
140
|
+
| 函数名 | 参数 | 返回值 | 描述 | 示例 |
|
|
141
|
+
|--------|------|--------|------|------|
|
|
142
|
+
| `first` | `arr: any[]` 或 `...args: any[]` | `any` | 第一个元素 | `first([1,2,3])` → `1`<br>`first(1,2,3)` → `1` |
|
|
143
|
+
| `last` | `arr: any[]` 或 `...args: any[]` | `any` | 最后一个元素 | `last([1,2,3])` → `3`<br>`last(1,2,3)` → `3` |
|
|
144
|
+
|
|
145
|
+
## 注意事项
|
|
146
|
+
|
|
147
|
+
1. **参数类型**:所有函数参数都经过类型转换,字符串会自动转为数字等
|
|
148
|
+
2. **空值处理**:大部分函数对空值有安全的处理机制
|
|
149
|
+
3. **错误处理**:函数调用出错时会抛出清晰的错误信息
|
|
150
|
+
4. **性能优化**:常用函数做了性能优化,适合高频调用
|
|
151
|
+
|
|
152
|
+
## 使用示例
|
|
153
|
+
|
|
154
|
+
```javascript
|
|
155
|
+
import { utils } from 'sh-tools'
|
|
156
|
+
|
|
157
|
+
// 数学计算
|
|
158
|
+
utils.calculate("abs(-10) + pow(2, 3)") // 18
|
|
159
|
+
|
|
160
|
+
// 数组操作
|
|
161
|
+
utils.calculate("sum([1,2,3,4,5]) / length([1,2,3,4,5])") // 3
|
|
162
|
+
|
|
163
|
+
// 字符串处理
|
|
164
|
+
utils.calculate("trim(' hello ') + ' ' + camelCase('world_test')") // "hello worldTest"
|
|
165
|
+
|
|
166
|
+
// 日期计算
|
|
167
|
+
utils.calculate("getDayDiff('2024-01-01', '2024-01-10') + getHourDiff('10:00', '12:30')") // 12.5
|
|
168
|
+
|
|
169
|
+
// 对象操作
|
|
170
|
+
utils.calculate("merge({a:1}, {b:2}, {c:3})") // {a:1, b:2, c:3}
|
|
171
|
+
```
|
|
33
172
|
|
|
34
|
-
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
|
|
35
|
-
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
|
|
36
|
-
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
|
|
37
|
-
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
|
|
38
|
-
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
|
|
39
|
-
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sh-tools",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.11",
|
|
4
4
|
"description": "基于fetch和xe-utils二次封装,支持宏公式计算",
|
|
5
5
|
"main": "packages/index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"author": "神秘的sh",
|
|
14
14
|
"license": "ISC",
|
|
15
15
|
"dependencies": {
|
|
16
|
-
"xe-utils": "^3.8.
|
|
16
|
+
"xe-utils": "^3.8.4"
|
|
17
17
|
},
|
|
18
18
|
"devDependencies": {
|
|
19
19
|
"@babel/core": "^7.12.16",
|
package/packages/expr/index.js
CHANGED
|
@@ -1,542 +1,550 @@
|
|
|
1
|
-
import
|
|
1
|
+
import utils from '../utils'
|
|
2
|
+
|
|
3
|
+
// ======================== Token 配置 ========================
|
|
4
|
+
export const TOKEN_TYPES = [
|
|
5
|
+
{ type: 'JSON', reg: /#JSON#[\s\S]*?#JSON#/, handler: token => token },
|
|
6
|
+
{ type: 'STRING', reg: /(["'])(.*?)\1/, handler: token => token.slice(1, -1) },
|
|
7
|
+
{ type: 'NUMBER', reg: /\d+\.?\d*|\.\d+/, handler: token => Number(token) },
|
|
8
|
+
{
|
|
9
|
+
type: 'KEYWORD',
|
|
10
|
+
reg: /\b(?:if|else|null|undefined|true|false)\b/,
|
|
11
|
+
handler: token => {
|
|
12
|
+
switch (token) {
|
|
13
|
+
case 'null':
|
|
14
|
+
return null
|
|
15
|
+
case 'undefined':
|
|
16
|
+
return undefined
|
|
17
|
+
case 'true':
|
|
18
|
+
return true
|
|
19
|
+
case 'false':
|
|
20
|
+
return false
|
|
21
|
+
default:
|
|
22
|
+
return token
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
{ type: 'IDENTIFIER', reg: /[a-zA-Z_$][a-zA-Z0-9_$]*/, handler: token => token },
|
|
27
|
+
{ type: 'OPERATOR', reg: /===|!==|==|!=|<=|>=|<<|>>|>>>|\|\||&&|\*\*|[,.+\-*/%^&|<>!?()\[\]:]/, handler: token => token }
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
export const OPERATOR_CONFIG = {
|
|
31
|
+
// 三元运算符
|
|
32
|
+
'?': { precedence: 1, associativity: 'right', isTernary: true, fn: (c, a, b) => (c ? a : b) },
|
|
33
|
+
// 逻辑运算符
|
|
34
|
+
'||': { precedence: 2, associativity: 'left', fn: (a, b) => a || b },
|
|
35
|
+
'&&': { precedence: 3, associativity: 'left', fn: (a, b) => a && b },
|
|
36
|
+
// 位运算符
|
|
37
|
+
'|': { precedence: 4, associativity: 'left', fn: (a, b) => a | b },
|
|
38
|
+
'^': { precedence: 5, associativity: 'left', fn: (a, b) => a ^ b },
|
|
39
|
+
'&': { precedence: 6, associativity: 'left', fn: (a, b) => a & b },
|
|
40
|
+
// 比较运算符
|
|
41
|
+
'==': { precedence: 7, associativity: 'left', fn: (a, b) => a == b },
|
|
42
|
+
'!=': { precedence: 7, associativity: 'left', fn: (a, b) => a != b },
|
|
43
|
+
'===': { precedence: 7, associativity: 'left', fn: utils.isEqual },
|
|
44
|
+
'!==': { precedence: 7, associativity: 'left', fn: (a, b) => a !== b },
|
|
45
|
+
'<': { precedence: 8, associativity: 'left', fn: (a, b) => utils.compareValue(a, b) },
|
|
46
|
+
'>': { precedence: 8, associativity: 'left', fn: (a, b) => utils.compareValue(b, a) },
|
|
47
|
+
'<=': { precedence: 8, associativity: 'left', fn: (a, b) => !utils.compareValue(b, a) },
|
|
48
|
+
'>=': { precedence: 8, associativity: 'left', fn: (a, b) => !utils.compareValue(a, b) },
|
|
49
|
+
// 算术运算符
|
|
50
|
+
'+': { precedence: 10, associativity: 'left', fn: utils.add },
|
|
51
|
+
'-': { precedence: 10, associativity: 'left', fn: utils.subtract },
|
|
52
|
+
'*': { precedence: 11, associativity: 'left', fn: utils.multiply },
|
|
53
|
+
'/': { precedence: 11, associativity: 'left', fn: utils.divide },
|
|
54
|
+
'%': { precedence: 11, associativity: 'left', fn: (a, b) => a % b },
|
|
55
|
+
'**': { precedence: 12, associativity: 'right', fn: (a, b) => Math.pow(a, b) },
|
|
56
|
+
// 一元运算符
|
|
57
|
+
'!': { precedence: 13, associativity: 'right', isUnary: true, fn: a => !a },
|
|
58
|
+
'~': { precedence: 13, associativity: 'right', isUnary: true, fn: a => ~a }
|
|
59
|
+
}
|
|
2
60
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
*/
|
|
8
|
-
class ExprEvaluator {
|
|
9
|
-
// 静态常量 - 仅保留核心方法
|
|
10
|
-
static MATH_METHODS = ['abs', 'sin', 'cos', 'tan', 'log', 'exp', 'pow']
|
|
11
|
-
static UTIL_METHODS = {
|
|
12
|
-
base: [
|
|
13
|
-
'isNaN',
|
|
14
|
-
'isFinite',
|
|
15
|
-
'isArray',
|
|
16
|
-
'isFloat',
|
|
17
|
-
'isInteger',
|
|
18
|
-
'isBoolean',
|
|
19
|
-
'isString',
|
|
20
|
-
'isNumber',
|
|
21
|
-
'isPlainObject',
|
|
22
|
-
'isDate',
|
|
23
|
-
'isEmpty',
|
|
24
|
-
'isNull',
|
|
25
|
-
'isMatch',
|
|
26
|
-
'isEqual',
|
|
27
|
-
'getSize',
|
|
28
|
-
'first',
|
|
29
|
-
'last'
|
|
30
|
-
],
|
|
61
|
+
// ======================== 工具函数 ========================
|
|
62
|
+
function getUtilsFunctions() {
|
|
63
|
+
const utilMethods = {
|
|
64
|
+
base: ['isNaN', 'isArray', 'isFloat', 'isInteger', 'isBoolean', 'isString', 'isNumber', 'isPlainObject', 'isDate', 'isEmpty', 'isNull', 'isMatch', 'isEqual', 'getSize', 'first', 'last'],
|
|
31
65
|
object: ['has', 'get', 'assign', 'merge', 'pick', 'omit'],
|
|
32
|
-
array: [
|
|
33
|
-
|
|
34
|
-
'indexOf',
|
|
35
|
-
'includes',
|
|
36
|
-
'includeArrays',
|
|
37
|
-
'sum',
|
|
38
|
-
'mean',
|
|
39
|
-
'zip',
|
|
40
|
-
'unzip',
|
|
41
|
-
'uniq',
|
|
42
|
-
'union',
|
|
43
|
-
'flatten',
|
|
44
|
-
'pluck',
|
|
45
|
-
'invoke',
|
|
46
|
-
'orderBy',
|
|
47
|
-
'groupBy',
|
|
48
|
-
'countBy',
|
|
49
|
-
'toArrayTree',
|
|
50
|
-
'toTreeArray'
|
|
51
|
-
],
|
|
52
|
-
date: ['toDateString', 'getYearDiff', 'getMonthDiff', 'getDayDiff', 'getHourDiff', 'getMinuteDiff', 'getSecondDiff', 'getYearDay', 'getYearWeek', 'getMonthWeek', 'getDayOfMonth'],
|
|
66
|
+
array: ['slice', 'indexOf', 'includes', 'includeArrays', 'sum', 'mean', 'unzip', 'uniq', 'union', 'flatten', 'pluck', 'invoke', 'orderBy', 'groupBy', 'countBy', 'toArrayTree', 'toTreeArray'],
|
|
67
|
+
date: ['now', 'timestamp', 'toDateString', 'getYearDiff', 'getMonthDiff', 'getDayDiff', 'getHourDiff', 'getMinuteDiff', 'getSecondDiff', 'getDayOfMonth'],
|
|
53
68
|
number: ['random', 'min', 'max', 'ceil', 'floor', 'round', 'truncate', 'toFixed', 'toNumber', 'toNumberString', 'toInteger', 'add', 'subtract', 'multiply', 'divide'],
|
|
54
|
-
string: ['toValueString', 'trim', 'trimLeft', 'trimRight', 'camelCase', 'kebabCase'
|
|
69
|
+
string: ['toValueString', 'trim', 'trimLeft', 'trimRight', 'camelCase', 'kebabCase']
|
|
55
70
|
}
|
|
71
|
+
return Object.values(utilMethods)
|
|
72
|
+
.flat()
|
|
73
|
+
.reduce((acc, method) => {
|
|
74
|
+
if (typeof utils[method] === 'function') acc[method] = utils[method]
|
|
75
|
+
else if (process.env.NODE_ENV === 'development') console.warn(`[ExprEvaluator] utils方法不存在: ${method}`)
|
|
76
|
+
return acc
|
|
77
|
+
}, {})
|
|
78
|
+
}
|
|
56
79
|
|
|
57
|
-
|
|
58
|
-
|
|
80
|
+
function getBuiltinFunctions() {
|
|
81
|
+
return {
|
|
82
|
+
...Object.fromEntries(['abs', 'sin', 'cos', 'tan', 'log', 'exp', 'pow'].map(name => [name, Math[name]])),
|
|
83
|
+
...getUtilsFunctions(),
|
|
84
|
+
startsWith: (str, value) => String(str || '').startsWith(value),
|
|
85
|
+
endsWith: (str, value) => String(str || '').endsWith(value),
|
|
86
|
+
length: value => value.length
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function tokensToExpr(tokens, start, end) {
|
|
91
|
+
return tokens
|
|
92
|
+
.slice(start, end)
|
|
93
|
+
.map(t => t.raw)
|
|
94
|
+
.join('')
|
|
95
|
+
.replace(/\s+/g, ' ')
|
|
96
|
+
.trim()
|
|
97
|
+
}
|
|
59
98
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
99
|
+
// ======================== 分词器 ========================
|
|
100
|
+
class Tokenizer {
|
|
101
|
+
tokenize(expr) {
|
|
102
|
+
const normalizedExpr = expr.replace(/[\n\r]/g, ' ').trim()
|
|
103
|
+
if (!normalizedExpr) throw new Error('表达式不能为空')
|
|
104
|
+
const tokens = []
|
|
105
|
+
let remaining = normalizedExpr
|
|
106
|
+
while (remaining) {
|
|
107
|
+
remaining = remaining.trim()
|
|
108
|
+
if (!remaining) break
|
|
109
|
+
let matchedType = null
|
|
110
|
+
let matchedValue = ''
|
|
111
|
+
for (const type of TOKEN_TYPES) {
|
|
112
|
+
const match = type.reg.exec(remaining)
|
|
113
|
+
if (match && match.index === 0) {
|
|
114
|
+
matchedType = type
|
|
115
|
+
matchedValue = match[0]
|
|
116
|
+
break
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (!matchedType) throw new Error(`无法识别的字符: ${remaining[0]}`)
|
|
120
|
+
tokens.push({
|
|
121
|
+
type: matchedType.type,
|
|
122
|
+
value: matchedType.handler(matchedValue),
|
|
123
|
+
raw: matchedValue
|
|
124
|
+
})
|
|
125
|
+
remaining = remaining.slice(matchedValue.length)
|
|
126
|
+
}
|
|
127
|
+
return tokens
|
|
65
128
|
}
|
|
129
|
+
}
|
|
66
130
|
|
|
131
|
+
// ======================== 解析器(简化日志版本) ========================
|
|
132
|
+
class Parser {
|
|
67
133
|
constructor() {
|
|
68
|
-
this.functions =
|
|
69
|
-
this.operators = {
|
|
70
|
-
this.
|
|
71
|
-
this.
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
this.
|
|
134
|
+
this.functions = getBuiltinFunctions()
|
|
135
|
+
this.operators = { ...OPERATOR_CONFIG }
|
|
136
|
+
this.tokens = []
|
|
137
|
+
this.pos = 0
|
|
138
|
+
this.enableLog = true
|
|
139
|
+
|
|
140
|
+
// 日志相关 - 简化处理
|
|
141
|
+
this.executionLog = [] // 存储原始日志对象
|
|
142
|
+
this.idCounter = 1
|
|
143
|
+
this.parentStack = [] // 存储父节点的ID
|
|
76
144
|
}
|
|
77
145
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
* @returns {number|string} 归一化后的值(日期转时间戳,数字串转数字,其余转字符串)
|
|
83
|
-
*/
|
|
84
|
-
_normalizeCompareValue(value) {
|
|
85
|
-
// 1. 处理日期类型(日期对象/可解析的日期字符串)
|
|
86
|
-
if (value instanceof Date) {
|
|
87
|
-
return value.getTime() // 转时间戳(数字)
|
|
146
|
+
registerFunction(name, fn, override = false) {
|
|
147
|
+
if (typeof name === 'object') {
|
|
148
|
+
Object.entries(name).forEach(([key, func]) => this.registerFunction(key, func, override))
|
|
149
|
+
return
|
|
88
150
|
}
|
|
89
|
-
if (typeof
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
// 普通字符串(去空格后比较)
|
|
101
|
-
return value.trim()
|
|
151
|
+
if (typeof fn !== 'function') throw new Error('注册的必须是函数')
|
|
152
|
+
if (!override && this.functions[name]) {
|
|
153
|
+
console.warn(`[ExprEvaluator] 函数 ${name} 已存在,使用 override=true 覆盖`)
|
|
154
|
+
return
|
|
155
|
+
}
|
|
156
|
+
this.functions[name] = fn
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
extendOperator(symbol, config, override = false) {
|
|
160
|
+
if (!config.precedence || !config.associativity || !config.fn) {
|
|
161
|
+
throw new Error('运算符配置必须包含 precedence、associativity、fn')
|
|
102
162
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
return
|
|
163
|
+
if (!override && this.operators[symbol]) {
|
|
164
|
+
console.warn(`[ExprEvaluator] 运算符 ${symbol} 已存在,使用 override=true 覆盖`)
|
|
165
|
+
return
|
|
106
166
|
}
|
|
107
|
-
|
|
108
|
-
return String(value)
|
|
167
|
+
this.operators[symbol] = config
|
|
109
168
|
}
|
|
110
169
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
// 2. 初始化工具函数
|
|
125
|
-
this._cachedUtilMethods = Object.values(ExprEvaluator.UTIL_METHODS).flat()
|
|
126
|
-
this._cachedUtilMethods.forEach(method => {
|
|
127
|
-
if (typeof utils[method] === 'function') {
|
|
128
|
-
this.functions[method] = utils[method]
|
|
129
|
-
} else if (process.env.NODE_ENV === 'development') {
|
|
130
|
-
console.warn(`[ExprEvaluator] 工具方法不存在: ${method}`)
|
|
131
|
-
}
|
|
132
|
-
})
|
|
133
|
-
|
|
134
|
-
// 3. 初始化核心运算符
|
|
135
|
-
this.operators = {
|
|
136
|
-
'?:': { precedence: 1, associativity: 'right', ternary: true, fn: (c, a, b) => (c ? a : b) },
|
|
137
|
-
'||': { precedence: 1, associativity: 'left', fn: (a, b) => a || b },
|
|
138
|
-
'&&': { precedence: 2, associativity: 'left', fn: (a, b) => a && b },
|
|
139
|
-
'|': { precedence: 3, associativity: 'left', fn: (a, b) => a | b },
|
|
140
|
-
'^': { precedence: 4, associativity: 'left', fn: (a, b) => a ^ b },
|
|
141
|
-
'&': { precedence: 5, associativity: 'left', fn: (a, b) => a & b },
|
|
142
|
-
'==': { precedence: 6, associativity: 'left', fn: (a, b) => a == b },
|
|
143
|
-
'!=': { precedence: 6, associativity: 'left', fn: (a, b) => a != b },
|
|
144
|
-
'!==': { precedence: 6, associativity: 'left', fn: (a, b) => a !== b },
|
|
145
|
-
'<': { precedence: 7, associativity: 'left', fn: (a, b) => this._normalizeCompareValue(a) < this._normalizeCompareValue(b) },
|
|
146
|
-
'>': { precedence: 7, associativity: 'left', fn: (a, b) => this._normalizeCompareValue(a) > this._normalizeCompareValue(b) },
|
|
147
|
-
'<=': { precedence: 7, associativity: 'left', fn: (a, b) => this._normalizeCompareValue(a) <= this._normalizeCompareValue(b) },
|
|
148
|
-
'>=': { precedence: 7, associativity: 'left', fn: (a, b) => this._normalizeCompareValue(a) >= this._normalizeCompareValue(b) },
|
|
149
|
-
'===': { precedence: 6, associativity: 'left', fn: utils.isEqual },
|
|
150
|
-
'+': { precedence: 9, associativity: 'left', fn: utils.add },
|
|
151
|
-
'-': { precedence: 9, associativity: 'left', fn: utils.subtract },
|
|
152
|
-
'*': { precedence: 10, associativity: 'left', fn: utils.multiply },
|
|
153
|
-
'/': { precedence: 10, associativity: 'left', fn: utils.divide },
|
|
154
|
-
'%': { precedence: 10, associativity: 'left', fn: (a, b) => a % b },
|
|
155
|
-
'!': { precedence: 12, associativity: 'right', prefix: true, fn: a => !a },
|
|
156
|
-
'~': { precedence: 12, associativity: 'right', prefix: true, fn: a => ~a }
|
|
170
|
+
// 创建日志条目
|
|
171
|
+
addLogEntry(expr, result) {
|
|
172
|
+
if (!this.enableLog) return null
|
|
173
|
+
|
|
174
|
+
const id = this.idCounter++
|
|
175
|
+
const parentId = this.parentStack.length > 0 ? this.parentStack[this.parentStack.length - 1] : null
|
|
176
|
+
|
|
177
|
+
const logEntry = {
|
|
178
|
+
id,
|
|
179
|
+
parentId,
|
|
180
|
+
expr,
|
|
181
|
+
result,
|
|
182
|
+
children: []
|
|
157
183
|
}
|
|
158
184
|
|
|
159
|
-
this.
|
|
185
|
+
this.executionLog.push(logEntry)
|
|
186
|
+
return id
|
|
160
187
|
}
|
|
161
188
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
189
|
+
// 进入上下文
|
|
190
|
+
enterContext(id) {
|
|
191
|
+
this.parentStack.push(id)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// 退出上下文
|
|
195
|
+
exitContext() {
|
|
196
|
+
this.parentStack.pop()
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
parse(tokens, enableLog = true) {
|
|
200
|
+
this.tokens = tokens
|
|
201
|
+
this.pos = 0
|
|
202
|
+
this.enableLog = enableLog
|
|
203
|
+
|
|
204
|
+
// 重置状态
|
|
205
|
+
this.executionLog = []
|
|
206
|
+
this.idCounter = 1
|
|
207
|
+
this.parentStack = []
|
|
208
|
+
|
|
209
|
+
const result = this.parseExpression()
|
|
180
210
|
|
|
181
|
-
if (this.
|
|
182
|
-
|
|
211
|
+
if (this.pos < tokens.length) {
|
|
212
|
+
const remaining = tokens
|
|
213
|
+
.slice(this.pos)
|
|
214
|
+
.map(t => t.raw)
|
|
215
|
+
.join('')
|
|
216
|
+
throw new Error(`表达式多余内容: ${remaining}`)
|
|
183
217
|
}
|
|
184
|
-
|
|
185
|
-
return
|
|
218
|
+
|
|
219
|
+
return { result, executionLog: this.executionLog }
|
|
186
220
|
}
|
|
187
221
|
|
|
188
|
-
|
|
189
|
-
* 解析数组字面量
|
|
190
|
-
* @private
|
|
191
|
-
* @returns {Array} 解析后的数组
|
|
192
|
-
*/
|
|
193
|
-
parseArrayLiteral() {
|
|
222
|
+
parseExpression(precedence = 1) {
|
|
194
223
|
const startPos = this.pos
|
|
195
|
-
this.
|
|
196
|
-
|
|
224
|
+
let left = this.parsePrimary()
|
|
225
|
+
|
|
226
|
+
while (this.peek() && this.isOperator(this.peek()) && this.getOperatorPrecedence(this.peek()) >= precedence) {
|
|
227
|
+
const opToken = this.consume()
|
|
228
|
+
const opConfig = this.operators[opToken.value]
|
|
229
|
+
|
|
230
|
+
if (opConfig?.isTernary) {
|
|
231
|
+
// 三元运算符特殊处理
|
|
232
|
+
const condition = left
|
|
233
|
+
const conditionExpr = tokensToExpr(this.tokens, startPos, this.pos - 1)
|
|
234
|
+
|
|
235
|
+
// 记录条件
|
|
236
|
+
const conditionId = this.addLogEntry(conditionExpr, condition)
|
|
237
|
+
|
|
238
|
+
// 记录三元表达式开始
|
|
239
|
+
const ternaryStartPos = startPos
|
|
240
|
+
|
|
241
|
+
// 处理真分支
|
|
242
|
+
this.enterContext(conditionId)
|
|
243
|
+
const trueBranch = this.parseExpression(1)
|
|
244
|
+
this.exitContext()
|
|
245
|
+
|
|
246
|
+
this.consumeToken('OPERATOR', ':')
|
|
197
247
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
this.
|
|
202
|
-
|
|
203
|
-
|
|
248
|
+
// 处理假分支
|
|
249
|
+
this.enterContext(conditionId)
|
|
250
|
+
const falseBranch = this.parseExpression(1)
|
|
251
|
+
this.exitContext()
|
|
252
|
+
|
|
253
|
+
const result = opConfig.fn(condition, trueBranch, falseBranch)
|
|
254
|
+
|
|
255
|
+
// 记录完整的三元表达式
|
|
256
|
+
const fullExpr = tokensToExpr(this.tokens, ternaryStartPos, this.pos)
|
|
257
|
+
this.addLogEntry(fullExpr, result)
|
|
258
|
+
|
|
259
|
+
left = result
|
|
260
|
+
continue
|
|
204
261
|
}
|
|
205
|
-
}
|
|
206
262
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
}
|
|
210
|
-
this.pos++
|
|
211
|
-
return arr
|
|
212
|
-
}
|
|
263
|
+
const nextPrecedence = opConfig.associativity === 'left' ? opConfig.precedence + 1 : opConfig.precedence
|
|
264
|
+
const right = this.parseExpression(nextPrecedence)
|
|
213
265
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
JSON.parse(jsonStr)
|
|
224
|
-
return true
|
|
225
|
-
} catch {
|
|
226
|
-
return false
|
|
266
|
+
// 记录运算符表达式
|
|
267
|
+
if (this.enableLog) {
|
|
268
|
+
const leftStr = typeof left === 'object' ? JSON.stringify(left) : String(left)
|
|
269
|
+
const rightStr = typeof right === 'object' ? JSON.stringify(right) : String(right)
|
|
270
|
+
const expr = `${leftStr} ${opToken.value} ${rightStr}`
|
|
271
|
+
this.addLogEntry(expr, opConfig.fn(left, right))
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
left = opConfig.fn(left, right)
|
|
227
275
|
}
|
|
276
|
+
|
|
277
|
+
return left
|
|
228
278
|
}
|
|
229
279
|
|
|
230
|
-
/**
|
|
231
|
-
* 解析基础Token
|
|
232
|
-
* @private
|
|
233
|
-
* @returns {any} 解析后的值
|
|
234
|
-
*/
|
|
235
280
|
parsePrimary() {
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
//
|
|
240
|
-
if (
|
|
241
|
-
this.
|
|
242
|
-
const jsonMatch = currentToken.match(/#JSON#([\s\S]*?)#JSON#/)
|
|
243
|
-
if (!jsonMatch || !this._isValidJson(jsonMatch[1])) {
|
|
244
|
-
throw new Error(`JSON解析失败:${jsonMatch?.[1] || currentToken}(原Token:${currentToken})`)
|
|
245
|
-
}
|
|
246
|
-
return JSON.parse(jsonMatch[1])
|
|
281
|
+
const token = this.peek()
|
|
282
|
+
if (!token) throw new Error('表达式意外结束')
|
|
283
|
+
|
|
284
|
+
// if-else 表达式
|
|
285
|
+
if (token.type === 'KEYWORD' && token.value === 'if') {
|
|
286
|
+
return this.parseIfElse()
|
|
247
287
|
}
|
|
248
288
|
|
|
249
|
-
//
|
|
250
|
-
if (
|
|
251
|
-
this.
|
|
252
|
-
return currentToken.slice(1, -1)
|
|
289
|
+
// 括号表达式
|
|
290
|
+
if (token.type === 'OPERATOR' && token.value === '(') {
|
|
291
|
+
return this.parseParenthesizedExpression()
|
|
253
292
|
}
|
|
254
293
|
|
|
255
|
-
//
|
|
256
|
-
if (
|
|
294
|
+
// JSON
|
|
295
|
+
if (token.type === 'JSON') {
|
|
296
|
+
return this.parseJsonLiteral()
|
|
297
|
+
}
|
|
257
298
|
|
|
258
|
-
//
|
|
259
|
-
if (
|
|
260
|
-
this.
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
throw new Error(`括号未闭合:缺少 )(当前Token:${this.tokens[this.pos] || '空'}, 位置:${this.pos})`)
|
|
299
|
+
// 字面量
|
|
300
|
+
if (['STRING', 'NUMBER', 'KEYWORD'].includes(token.type)) {
|
|
301
|
+
const value = this.consume().value
|
|
302
|
+
if (this.enableLog && token.type !== 'KEYWORD') {
|
|
303
|
+
this.addLogEntry(token.raw, value)
|
|
264
304
|
}
|
|
265
|
-
|
|
266
|
-
return res
|
|
305
|
+
return value
|
|
267
306
|
}
|
|
268
307
|
|
|
269
|
-
//
|
|
270
|
-
if (
|
|
271
|
-
const
|
|
272
|
-
this.
|
|
308
|
+
// 一元运算符
|
|
309
|
+
if (this.isUnaryOperator(token)) {
|
|
310
|
+
const opToken = this.consume()
|
|
311
|
+
const opConfig = this.operators[opToken.value]
|
|
312
|
+
const operand = this.parsePrimary()
|
|
313
|
+
const result = opConfig.fn(operand)
|
|
273
314
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
if (!this.functions[funcName]) throw new Error(`未定义函数: ${funcName}`)
|
|
278
|
-
return this.functions[funcName](...args)
|
|
315
|
+
if (this.enableLog) {
|
|
316
|
+
const expr = `${opToken.value}${operand}`
|
|
317
|
+
this.addLogEntry(expr, result)
|
|
279
318
|
}
|
|
280
319
|
|
|
281
|
-
|
|
320
|
+
return result
|
|
282
321
|
}
|
|
283
322
|
|
|
284
|
-
//
|
|
285
|
-
if (
|
|
286
|
-
this.
|
|
287
|
-
return Number(currentToken)
|
|
323
|
+
// 数组
|
|
324
|
+
if (token.type === 'OPERATOR' && token.value === '[') {
|
|
325
|
+
return this.parseArrayLiteral()
|
|
288
326
|
}
|
|
289
327
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
// ========== 精简后的解析链(仅保留核心运算) ==========
|
|
294
|
-
/**
|
|
295
|
-
* 解析乘/除/取模运算
|
|
296
|
-
* @private
|
|
297
|
-
* @returns {number} 运算结果
|
|
298
|
-
*/
|
|
299
|
-
parseMultiplicative() {
|
|
300
|
-
let res = this.parsePrimary()
|
|
301
|
-
while (ExprEvaluator.OP_MAP.arithmetic[this.tokens[this.pos]] && ['*', '/', '%'].includes(this.tokens[this.pos])) {
|
|
302
|
-
const op = this.tokens[this.pos]
|
|
303
|
-
this.pos++
|
|
304
|
-
res = this.operators[op].fn(res, this.parsePrimary())
|
|
328
|
+
// 函数调用
|
|
329
|
+
if (token.type === 'IDENTIFIER') {
|
|
330
|
+
return this.parseFunctionCall()
|
|
305
331
|
}
|
|
306
|
-
return res
|
|
307
|
-
}
|
|
308
332
|
|
|
309
|
-
|
|
310
|
-
* 解析加/减运算
|
|
311
|
-
* @private
|
|
312
|
-
* @returns {number} 运算结果
|
|
313
|
-
*/
|
|
314
|
-
parseAdditive() {
|
|
315
|
-
let res = this.parseMultiplicative()
|
|
316
|
-
while (ExprEvaluator.OP_MAP.arithmetic[this.tokens[this.pos]] && ['+', '-'].includes(this.tokens[this.pos])) {
|
|
317
|
-
const op = this.tokens[this.pos]
|
|
318
|
-
this.pos++
|
|
319
|
-
res = this.operators[op].fn(res, this.parseMultiplicative())
|
|
320
|
-
}
|
|
321
|
-
return res
|
|
333
|
+
throw new Error(`无效Token: ${token.raw}`)
|
|
322
334
|
}
|
|
323
335
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
* @returns {boolean} 运算结果
|
|
328
|
-
*/
|
|
329
|
-
parseRelational() {
|
|
330
|
-
let res = this.parseAdditive()
|
|
331
|
-
while (ExprEvaluator.OP_MAP.relational[this.tokens[this.pos]]) {
|
|
332
|
-
const op = this.tokens[this.pos]
|
|
333
|
-
this.pos++
|
|
334
|
-
res = this.operators[op].fn(res, this.parseAdditive())
|
|
335
|
-
}
|
|
336
|
-
return res
|
|
337
|
-
}
|
|
336
|
+
parseParenthesizedExpression() {
|
|
337
|
+
const startPos = this.pos
|
|
338
|
+
this.consumeToken('OPERATOR', '(')
|
|
338
339
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
* @returns {boolean} 运算结果
|
|
343
|
-
*/
|
|
344
|
-
parseEquality() {
|
|
345
|
-
let res = this.parseRelational()
|
|
346
|
-
while (ExprEvaluator.OP_MAP.equality[this.tokens[this.pos]]) {
|
|
347
|
-
const op = this.tokens[this.pos]
|
|
348
|
-
this.pos++
|
|
349
|
-
res = this.operators[op].fn(res, this.parseRelational())
|
|
350
|
-
}
|
|
351
|
-
return res
|
|
352
|
-
}
|
|
340
|
+
// 记录括号开始
|
|
341
|
+
const parentId = this.addLogEntry('(', null)
|
|
342
|
+
this.enterContext(parentId)
|
|
353
343
|
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
parseBitwiseAnd() {
|
|
360
|
-
let res = this.parseEquality()
|
|
361
|
-
while (this.tokens[this.pos] === '&') {
|
|
362
|
-
this.pos++
|
|
363
|
-
res = this.operators['&'].fn(res, this.parseEquality())
|
|
344
|
+
let result
|
|
345
|
+
if (this.matchToken('KEYWORD', 'if')) {
|
|
346
|
+
result = this.parseIfElse()
|
|
347
|
+
} else {
|
|
348
|
+
result = this.parseExpression(1)
|
|
364
349
|
}
|
|
365
|
-
return res
|
|
366
|
-
}
|
|
367
350
|
|
|
368
|
-
|
|
369
|
-
* 解析按位异或运算
|
|
370
|
-
* @private
|
|
371
|
-
* @returns {number} 运算结果
|
|
372
|
-
*/
|
|
373
|
-
parseBitwiseXor() {
|
|
374
|
-
let res = this.parseBitwiseAnd()
|
|
375
|
-
while (this.tokens[this.pos] === '^') {
|
|
376
|
-
this.pos++
|
|
377
|
-
res = this.operators['^'].fn(res, this.parseBitwiseAnd())
|
|
378
|
-
}
|
|
379
|
-
return res
|
|
380
|
-
}
|
|
351
|
+
this.consumeToken('OPERATOR', ')')
|
|
381
352
|
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
let res = this.parseBitwiseXor()
|
|
389
|
-
while (this.tokens[this.pos] === '|') {
|
|
390
|
-
this.pos++
|
|
391
|
-
res = this.operators['|'].fn(res, this.parseBitwiseXor())
|
|
353
|
+
// 更新括号表达式
|
|
354
|
+
const expr = tokensToExpr(this.tokens, startPos, this.pos)
|
|
355
|
+
const log = this.executionLog.find(l => l.id === parentId)
|
|
356
|
+
if (log) {
|
|
357
|
+
log.expr = expr
|
|
358
|
+
log.result = result
|
|
392
359
|
}
|
|
393
|
-
|
|
360
|
+
|
|
361
|
+
this.exitContext()
|
|
362
|
+
return result
|
|
394
363
|
}
|
|
395
364
|
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
365
|
+
parseJsonLiteral() {
|
|
366
|
+
const token = this.consume()
|
|
367
|
+
try {
|
|
368
|
+
const jsonStr = token.raw.slice(6, -6)
|
|
369
|
+
const result = JSON.parse(jsonStr)
|
|
370
|
+
|
|
371
|
+
if (this.enableLog) {
|
|
372
|
+
this.addLogEntry(token.raw, result)
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
return result
|
|
376
|
+
} catch (e) {
|
|
377
|
+
throw new Error(`JSON解析失败: ${token.raw},原因:${e.message}`)
|
|
406
378
|
}
|
|
407
|
-
return res
|
|
408
379
|
}
|
|
409
380
|
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
381
|
+
parseArrayLiteral() {
|
|
382
|
+
const startPos = this.pos
|
|
383
|
+
this.consumeToken('OPERATOR', '[')
|
|
384
|
+
|
|
385
|
+
// 记录数组开始
|
|
386
|
+
const arrayId = this.addLogEntry('[', null)
|
|
387
|
+
this.enterContext(arrayId)
|
|
388
|
+
|
|
389
|
+
const arr = []
|
|
390
|
+
|
|
391
|
+
if (!this.matchToken('OPERATOR', ']')) {
|
|
392
|
+
arr.push(this.parseExpression())
|
|
393
|
+
while (this.matchToken('OPERATOR', ',')) {
|
|
394
|
+
this.consumeToken('OPERATOR', ',')
|
|
395
|
+
arr.push(this.parseExpression())
|
|
396
|
+
}
|
|
420
397
|
}
|
|
421
|
-
return res
|
|
422
|
-
}
|
|
423
398
|
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
this.pos++
|
|
433
|
-
const a = this.parseTernaryCore()
|
|
434
|
-
if (this.tokens[this.pos] !== ':') throw new Error('三元运算符缺少冒号')
|
|
435
|
-
this.pos++
|
|
436
|
-
const b = this.parseTernaryCore()
|
|
437
|
-
res = this.operators['?:'].fn(res, a, b)
|
|
399
|
+
this.consumeToken('OPERATOR', ']')
|
|
400
|
+
|
|
401
|
+
// 更新数组表达式
|
|
402
|
+
const expr = tokensToExpr(this.tokens, startPos, this.pos)
|
|
403
|
+
const log = this.executionLog.find(l => l.id === arrayId)
|
|
404
|
+
if (log) {
|
|
405
|
+
log.expr = expr
|
|
406
|
+
log.result = arr
|
|
438
407
|
}
|
|
439
|
-
|
|
408
|
+
|
|
409
|
+
this.exitContext()
|
|
410
|
+
return arr
|
|
440
411
|
}
|
|
441
412
|
|
|
442
|
-
/**
|
|
443
|
-
* 解析if/else和三元运算
|
|
444
|
-
* @private
|
|
445
|
-
* @returns {any} 运算结果
|
|
446
|
-
*/
|
|
447
413
|
parseIfElse() {
|
|
448
|
-
|
|
449
|
-
this.pos++
|
|
414
|
+
const startPos = this.pos
|
|
450
415
|
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
}
|
|
454
|
-
this.pos++
|
|
416
|
+
this.consumeToken('KEYWORD', 'if')
|
|
417
|
+
this.consumeToken('OPERATOR', '(')
|
|
455
418
|
|
|
456
|
-
const condition = this.
|
|
457
|
-
|
|
458
|
-
throw new Error(`if语法错误:缺少右括号(当前Token:${this.tokens[this.pos] || '空'}, 位置:${this.pos})`)
|
|
459
|
-
}
|
|
460
|
-
this.pos++
|
|
419
|
+
const condition = this.parseExpression()
|
|
420
|
+
this.consumeToken('OPERATOR', ')')
|
|
461
421
|
|
|
462
|
-
const
|
|
463
|
-
if (this.tokens[this.pos] !== 'else') {
|
|
464
|
-
throw new Error(`if语法错误:缺少else关键字(当前Token:${this.tokens[this.pos] || '空'}, 位置:${this.pos})`)
|
|
465
|
-
}
|
|
466
|
-
this.pos++
|
|
422
|
+
const ifExpr = this.parseExpression()
|
|
467
423
|
|
|
468
|
-
|
|
469
|
-
return condition ? thenValue : elseValue
|
|
470
|
-
}
|
|
424
|
+
let elseExpr = undefined
|
|
471
425
|
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
* @private
|
|
475
|
-
* @returns {any} 运算结果
|
|
476
|
-
*/
|
|
477
|
-
parseTernary() {
|
|
478
|
-
return this.parseIfElse()
|
|
479
|
-
}
|
|
426
|
+
if (this.matchToken('KEYWORD', 'else')) {
|
|
427
|
+
this.consumeToken('KEYWORD', 'else')
|
|
480
428
|
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
* @private
|
|
484
|
-
* @param {string} expr 表达式
|
|
485
|
-
* @returns {Array} 分词结果
|
|
486
|
-
*/
|
|
487
|
-
_tokenize(expr) {
|
|
488
|
-
const tokens = []
|
|
489
|
-
const reg = new RegExp(ExprEvaluator.TOKEN_REG.source, 'g')
|
|
490
|
-
let match
|
|
491
|
-
|
|
492
|
-
while ((match = reg.exec(expr)) !== null) {
|
|
493
|
-
const token = match[0].trim()
|
|
494
|
-
if (!token) continue
|
|
495
|
-
|
|
496
|
-
if (token.includes('#JSON#')) {
|
|
497
|
-
tokens.push(token)
|
|
498
|
-
} else if (token.startsWith('"') || token.startsWith("'")) {
|
|
499
|
-
tokens.push(token)
|
|
500
|
-
} else if (/^\d+\.?\d*|\.\d+$/.test(token)) {
|
|
501
|
-
tokens.push(Number(token))
|
|
429
|
+
if (this.matchToken('KEYWORD', 'if')) {
|
|
430
|
+
elseExpr = this.parseIfElse()
|
|
502
431
|
} else {
|
|
503
|
-
|
|
432
|
+
elseExpr = this.parseExpression()
|
|
504
433
|
}
|
|
505
434
|
}
|
|
506
435
|
|
|
507
|
-
|
|
508
|
-
|
|
436
|
+
const result = condition ? ifExpr : elseExpr
|
|
437
|
+
|
|
438
|
+
if (this.enableLog) {
|
|
439
|
+
const fullExpr = tokensToExpr(this.tokens, startPos, this.pos)
|
|
440
|
+
this.addLogEntry(fullExpr, result)
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
return result
|
|
509
444
|
}
|
|
510
445
|
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
evaluate(expr) {
|
|
518
|
-
this._lazyInit()
|
|
446
|
+
parseFunctionCall() {
|
|
447
|
+
const startPos = this.pos
|
|
448
|
+
const funcName = this.consume().value
|
|
449
|
+
const openChar = this.matchToken('OPERATOR', '(') ? '(' : this.matchToken('OPERATOR', '[') ? '[' : null
|
|
450
|
+
if (!openChar) throw new Error(`不支持变量: ${funcName}(仅支持函数调用)`)
|
|
451
|
+
const closeChar = openChar === '(' ? ')' : ']'
|
|
519
452
|
|
|
520
|
-
|
|
521
|
-
const
|
|
522
|
-
|
|
453
|
+
// 记录函数调用开始
|
|
454
|
+
const funcId = this.addLogEntry(`${funcName}${openChar}`, null)
|
|
455
|
+
this.enterContext(funcId)
|
|
523
456
|
|
|
524
|
-
|
|
525
|
-
this.tokens = this._tokenize(normalizedExpr)
|
|
526
|
-
this.pos = 0
|
|
527
|
-
const result = this.parseTernary()
|
|
457
|
+
this.consumeToken('OPERATOR', openChar)
|
|
528
458
|
|
|
529
|
-
|
|
530
|
-
|
|
459
|
+
// 收集参数
|
|
460
|
+
const args = []
|
|
461
|
+
if (!this.matchToken('OPERATOR', closeChar)) {
|
|
462
|
+
args.push(this.parseExpression())
|
|
463
|
+
while (this.matchToken('OPERATOR', ',')) {
|
|
464
|
+
this.consumeToken('OPERATOR', ',')
|
|
465
|
+
args.push(this.parseExpression())
|
|
531
466
|
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
this.consumeToken('OPERATOR', closeChar)
|
|
470
|
+
|
|
471
|
+
// 执行函数调用
|
|
472
|
+
if (!this.functions[funcName]) {
|
|
473
|
+
throw new Error(`未定义函数: ${funcName}`)
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
const result = this.functions[funcName](...args)
|
|
532
477
|
|
|
478
|
+
// 更新函数调用表达式
|
|
479
|
+
const expr = tokensToExpr(this.tokens, startPos, this.pos)
|
|
480
|
+
const log = this.executionLog.find(l => l.id === funcId)
|
|
481
|
+
if (log) {
|
|
482
|
+
log.expr = expr
|
|
483
|
+
log.result = result
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
this.exitContext()
|
|
487
|
+
return result
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// ======================== 工具方法 ========================
|
|
491
|
+
peek() {
|
|
492
|
+
return this.tokens[this.pos]
|
|
493
|
+
}
|
|
494
|
+
consume() {
|
|
495
|
+
return this.tokens[this.pos++]
|
|
496
|
+
}
|
|
497
|
+
matchToken(type, value) {
|
|
498
|
+
const token = this.peek()
|
|
499
|
+
return token && token.type === type && token.value === value
|
|
500
|
+
}
|
|
501
|
+
consumeToken(type, value) {
|
|
502
|
+
if (!this.matchToken(type, value)) throw new Error(`缺少Token: ${value}`)
|
|
503
|
+
return this.consume()
|
|
504
|
+
}
|
|
505
|
+
isOperator(token) {
|
|
506
|
+
return token.type === 'OPERATOR' && !!this.operators[token.value]
|
|
507
|
+
}
|
|
508
|
+
isUnaryOperator(token) {
|
|
509
|
+
return this.isOperator(token) && this.operators[token.value]?.isUnary
|
|
510
|
+
}
|
|
511
|
+
getOperatorPrecedence(token) {
|
|
512
|
+
return this.operators[token.value]?.precedence || 0
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// ======================== 求值器 ========================
|
|
517
|
+
class ExprEvaluator {
|
|
518
|
+
constructor() {
|
|
519
|
+
this.tokenizer = new Tokenizer()
|
|
520
|
+
this.parser = new Parser()
|
|
521
|
+
}
|
|
522
|
+
registerFunction(name, fn, override = false) {
|
|
523
|
+
this.parser.registerFunction(name, fn, override)
|
|
524
|
+
}
|
|
525
|
+
extendOperator(symbol, config, override = false) {
|
|
526
|
+
this.parser.extendOperator(symbol, config, override)
|
|
527
|
+
}
|
|
528
|
+
evaluateLog(expr, enableLog = true) {
|
|
529
|
+
try {
|
|
530
|
+
const tokens = this.tokenizer.tokenize(expr)
|
|
531
|
+
const { result, executionLog } = this.parser.parse(tokens, enableLog)
|
|
532
|
+
return { result, log: utils.orderBy(executionLog, 'parentId'), treeLog: utils.toArrayTree(executionLog) }
|
|
533
|
+
} catch (error) {
|
|
534
|
+
throw new Error(`[ExprEvaluator] ${error.message}(原表达式:${expr})`)
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
evaluate(expr) {
|
|
538
|
+
try {
|
|
539
|
+
const tokens = this.tokenizer.tokenize(expr)
|
|
540
|
+
const { result } = this.parser.parse(tokens, false)
|
|
533
541
|
return result
|
|
534
542
|
} catch (error) {
|
|
535
|
-
throw new Error(
|
|
543
|
+
throw new Error(`[ExprEvaluator] ${error.message}(原表达式:${expr})`)
|
|
536
544
|
}
|
|
537
545
|
}
|
|
538
546
|
}
|
|
539
547
|
|
|
540
|
-
// 单例导出
|
|
541
|
-
const
|
|
542
|
-
export default
|
|
548
|
+
// ======================== 单例导出 ========================
|
|
549
|
+
const exprEvaluator = new ExprEvaluator()
|
|
550
|
+
export default exprEvaluator
|
package/packages/index.js
CHANGED
|
@@ -2,6 +2,25 @@ import http from './api'
|
|
|
2
2
|
import utils from './utils'
|
|
3
3
|
import expr from './expr'
|
|
4
4
|
|
|
5
|
+
// 再此扩展公式计算方法,防止循环依赖问题
|
|
6
|
+
utils.mixin({
|
|
7
|
+
calculate(formula, data) {
|
|
8
|
+
if (!formula) return ''
|
|
9
|
+
if (data && utils.isPlainObject(data)) {
|
|
10
|
+
formula = utils.format(formula, data, true)
|
|
11
|
+
}
|
|
12
|
+
return expr.evaluate(formula)
|
|
13
|
+
},
|
|
14
|
+
|
|
15
|
+
calculateLog(formula, data) {
|
|
16
|
+
if (!formula) return ''
|
|
17
|
+
if (data && utils.isPlainObject(data)) {
|
|
18
|
+
formula = utils.format(formula, data, true)
|
|
19
|
+
}
|
|
20
|
+
return expr.evaluateLog(formula)
|
|
21
|
+
}
|
|
22
|
+
})
|
|
23
|
+
|
|
5
24
|
export { http, utils, expr }
|
|
6
25
|
|
|
7
26
|
export default { http, utils, expr }
|
package/packages/utils/number.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import XEUtils from 'xe-utils'
|
|
2
|
-
import stringUtil from './string'
|
|
3
|
-
import formulaParser from '../expr'
|
|
4
2
|
|
|
5
3
|
export default {
|
|
6
4
|
truncate(num, digits) {
|
|
@@ -10,13 +8,5 @@ export default {
|
|
|
10
8
|
} else {
|
|
11
9
|
return XEUtils.floor(num, digits)
|
|
12
10
|
}
|
|
13
|
-
},
|
|
14
|
-
|
|
15
|
-
calculate(formula, data) {
|
|
16
|
-
if (!formula) return ''
|
|
17
|
-
if (data && XEUtils.isPlainObject(data)) {
|
|
18
|
-
formula = stringUtil.format(formula, data)
|
|
19
|
-
}
|
|
20
|
-
return formulaParser.evaluate(formula)
|
|
21
11
|
}
|
|
22
12
|
}
|
package/packages/utils/string.js
CHANGED
|
@@ -8,17 +8,17 @@ function getFormatKeys(format) {
|
|
|
8
8
|
}
|
|
9
9
|
|
|
10
10
|
// 格式化数据结构
|
|
11
|
-
function format(format, data) {
|
|
11
|
+
function format(format, data, addQuotes) {
|
|
12
12
|
let keys = getFormatKeys(format)
|
|
13
13
|
let formatStr = String(format)
|
|
14
14
|
keys.map((key, indexkey) => {
|
|
15
15
|
let value = XEUtils.get(data, key) || ''
|
|
16
16
|
let replaceValue = ''
|
|
17
17
|
if (value === undefined || value === null) {
|
|
18
|
-
replaceValue = '""'
|
|
18
|
+
replaceValue = addQuotes ? '""' : ''
|
|
19
19
|
} else if (typeof value === 'object' || Array.isArray(value)) {
|
|
20
|
-
replaceValue = `#JSON#${JSON.stringify(value)}#JSON#`
|
|
21
|
-
} else if (typeof value === 'string') {
|
|
20
|
+
replaceValue = addQuotes ? `#JSON#${JSON.stringify(value)}#JSON#` : JSON.stringify(value)
|
|
21
|
+
} else if (typeof value === 'string' && addQuotes) {
|
|
22
22
|
replaceValue = `"${value}"`
|
|
23
23
|
} else {
|
|
24
24
|
replaceValue = value
|
|
@@ -39,10 +39,26 @@ function randomStr(len = 32) {
|
|
|
39
39
|
return str
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
function normalize(val) {
|
|
43
|
+
if (val instanceof Date && !isNaN(val.getTime())) return val.getTime()
|
|
44
|
+
if (typeof val === 'string') {
|
|
45
|
+
const date = new Date(val)
|
|
46
|
+
if (!isNaN(date.getTime())) return date.getTime()
|
|
47
|
+
const num = Number(val)
|
|
48
|
+
return isNaN(num) ? val.trim() : num
|
|
49
|
+
}
|
|
50
|
+
return typeof val === 'number' ? val : String(val)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function compareValue(a, b) {
|
|
54
|
+
return normalize(a) < normalize(b)
|
|
55
|
+
}
|
|
56
|
+
|
|
42
57
|
export default {
|
|
43
58
|
randomStr,
|
|
44
59
|
getFormatKeys,
|
|
45
60
|
format,
|
|
61
|
+
compareValue,
|
|
46
62
|
replaceNutrim(str) {
|
|
47
63
|
return String(str).replace(/undefined|(^\s*)|(\s*$)/gi, '')
|
|
48
64
|
},
|