我一直在做一个简单的数学解说员,我被一个问题困住了。
我不知道如何在解释器中遍历对象。我的调度要么根本不工作,要么导致无限循环,直到Javascript达到它的最大内存量。
对于一个简单的2 + 2 + 3,解析器的结果应该如下所示
{
"operator": "+",
"left": {
"operator": "+",
"left": {
"type": "NUMBER",
"value": 2
},
"right": {
"type": "NUMBER",
"value": 2
}
},
"right": {
"type": "NUMBER",
"value": 3
}
}这是我做过的一个尝试。
interpret(node) {
node.left = this.parseNode(node.left);
node.right = this.parseNode(node.right);
return this.parseNum(node.left, node.right, node.operator);
}
parseNode(node) {
let left = node.left;
let right = node.right;
while (left != null) {
left = this.destructure(left);
}
while (right != null) {
right = this.destructure(right);
}
if (left == null && right == null) {
return { ...node };
} else {
return {
type: "NUMBER",
value: this.parseNum(left, right, node.operator),
};
}
}解析数字(parseNum)函数非常简单,因此我不需要共享它。它所做的就是取操作符,并在此基础上添加/乘/减/除前两项。
任何帮助都将不胜感激,谢谢。
发布于 2022-01-07 00:54:22
您想要的是递归地将每个节点缩减为一个值,方法是检查它.
如果节点已经是值节点,则只需返回值节点(
计算结果来创建一个新的值节点。
const root = {"operator":"+","left":{"operator":"+","left":{"type":"NUMBER","value":2},"right":{"type":"NUMBER","value":2}},"right":{"type":"NUMBER","value":3}}
// Operator functions
const operators = {
"+": (l, r) => l + r,
}
// Expression evaluation
const evaluate = ({ value: l }, { value: r }, operator) =>
operators[operator](l, r)
const isValueNode = node => "value" in node
// Reduce a node to a _value_ node
const reducer = (node) => {
// Already a value node? Just return it
if (isValueNode(node)) return node
return {
type: "NUMBER", // no idea what this is for ¯\_(ツ)_/¯
value: evaluate(
reducer(node.left), // recursively reduce the _left_ node
reducer(node.right), // recursively reduce the _right_ node
node.operator
)
}
}
console.log(reducer(root))
https://stackoverflow.com/questions/70615085
复制相似问题