解析javascript中的二进制表达式
作者:互联网
我有一个这样的表达:
{
"type": "BinaryExpression",
"operator": "OR",
"left": {
"type": "Literal",
"value": 1,
"raw": "1"
},
"right": {
"type": "BinaryExpression",
"operator": "AND",
"left": {
"type": "Literal",
"value": 2,
"raw": "2"
},
"right": {
"type": "Literal",
"value": 3,
"raw": "3"
}
}
}
我想将其转换为JS中的以下内容.
logic: 'OR'
filters: [
{1}
logic: 'AND'
filters: [
{2},
{3}
]
]
即,当有运算符时,我将放入Javascript对象的逻辑变量.之后,我将检查是否存在left和right属性.如果它们中的任何一个是文字,我将只添加到javascript对象的过滤器数组中.如果left和right属性是一个二进制表达式,那么在javascript对象中,我将重复上述过程.
我尝试了各种方法,但是以某种方式我会错过一些东西.所以,我在这里问. :
var currentFilter = {
'logic': null,
filters: []
};
test(expression, currentFilter);
function test(expression, currentFilter) {
while (expression.left != null && expression.right != null) {
currentFilter.logic = expression.operator;
if (expression.left.type === 'Literal') {
currentFilter.filters.push = expression.left.value;
} else if (expression.left.type === 'BinaryExpression') {
test(expression.left, currentFilter);
}
if (expression.right.type === 'Literal') {
currentFilter.filters.push = expression.right.value;
} else if (expression.right.type === 'BinaryExpression') {
test(expression.right, currentFilter);
}
}
}
解决方法:
看起来您与示例非常接近,并且正在尝试使用递归来构建所需的对象.您的失败原因可能是while循环,因为由于表达式未更新,它将陷入无限循环.这样的事情应该更像您想要的东西:
const exp = {
"type": "BinaryExpression",
"operator": "OR",
"left": {
"type": "Literal",
"value": 1,
"raw": "1"
},
"right": {
"type": "BinaryExpression",
"operator": "AND",
"left": {
"type": "Literal",
"value": 2,
"raw": "2"
},
"right": {
"type": "Literal",
"value": 3,
"raw": "3"
}
}
}
const parseValue = v => v.type === 'Literal' ? v.value : parseExp(v)
const parseExp = ({ operator, left, right }) => ({
logic: operator,
filters: [parseValue(left), parseValue(right)]
})
console.log(parseExp(exp))
标签:binary-tree,javascript,parsing 来源: https://codeday.me/bug/20191024/1923310.html