-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluate.ts
37 lines (35 loc) · 1.24 KB
/
evaluate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { Expression } from "./Expression.ts";
export function evaluate(ast: Expression): number {
if (ast.type === "NumericLiteral") {
return ast.value;
}
if (ast.type === "UnaryExpression") {
if (ast.operator === "-") {
return -1 * evaluate(ast.argument);
}
throw new Error(`Unary operator ${ast.operator} not supported`);
}
if (ast.type === "BinaryExpression") {
if (ast.operator === "-") {
return evaluate(ast.left) - evaluate(ast.right);
}
if (ast.operator === "*") {
return evaluate(ast.left) * evaluate(ast.right);
}
if (ast.operator === "+") {
return evaluate(ast.left) + evaluate(ast.right);
}
if (ast.operator === "/") {
const num1 = evaluate(ast.left);
const num2 = evaluate(ast.right);
const sign = Math.sign(num2) * Math.sign(num1);
return sign * Math.floor(Math.abs(num1) / Math.abs(num2));
//整数除法
}
throw new Error(`Binary operator ${ast.operator} not supported`);
}
if (ast.type === "ParenthesizedExpression") {
return evaluate(ast.expression);
}
throw Error("not support expression");
}