我有一个表达式:
( a || b && c ) && ( d || e )
a
、b
、c
、d
、e
都是之后会进行解析的函数,类型是() => boolean
,这个可以不用管
我想把这个表达式解析成一个变量,这样我可以用函数调用的形式来得到这个表达式的结果。
目前我想到的变量格式是这样的:
interface Expression {
type: 'and' | 'or',
children: Array<Expression>
}
const res: Expression = {
type: 'and',
children: [
{
type: 'or',
children: [
{ type: 'and', children: [a] }
{ type: 'and', children: [b, c] }
]
},
{
type: 'or',
children: [d, e]
}
]
}
type
为'and'
的表达式children
中的每个嵌套表达式都要为true
,此时这个表达式才是true
type
为'or'
的表达式则是children
里只要有一个为true
就行
现在我遇到的主要问题是括号没想到啥好办法去处理,因为我想要的表达式变量格式是按实际运算顺序排列的,但是原始的表达式是从左到右按书写顺序排列的
或者有啥更好的方式能做到说用函数的方式解析if表达式(不要eval
、new Function
)
简单的二元表达式解析,在线地址, evaluator我就不写了具体可以看一下我的这个项目代码