我一直在研究一個簡單的數學解釋器,但我遇到了一個問題。
我不知道如何在解釋器中回圈遍歷物件。我的嘗試要么根本不起作用,要么導致無限回圈,直到 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)函式很簡單,我覺得沒必要分享。它所做的只是使用運算子并在此基礎上加/乘/減/除前兩項。
任何幫助將不勝感激,謝謝。
uj5u.com熱心網友回復:
您想要的是通過檢查每個節點遞回地將每個節點減少為一個值,然后......
- 如果節點已經是值節點,則直接回傳
- 否則,通過將左右節點減少為單個值節點并使用運算子評估結果來創建新的值節點
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://www.uj5u.com/caozuo/405875.html
標籤:
