-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ast.test.ts
55 lines (44 loc) · 1.55 KB
/
Ast.test.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { AST } from "../AST";
import { Token, TokenType } from "../Types";
const numberToken = (value: string): Token => ({
type: TokenType.Number,
value,
});
const binaryToken = (value: string): Token => ({
type: TokenType.Binary,
value,
});
const unaryToken = (value: string): Token => ({ type: TokenType.Unary, value });
describe("AST", () => {
let ast: AST;
beforeEach(() => {
ast = new AST();
});
// Test for Add method (building the AST)
it("should correctly build AST for binary addition", () => {
const rpn: Token[] = [numberToken("3"), numberToken("4"), binaryToken("+")];
const rootNode = ast.Add(rpn);
expect(rootNode.value).toBe("+");
expect(rootNode.left?.value).toBe("3");
expect(rootNode.right?.value).toBe("4");
});
it("should correctly build AST for unary minus", () => {
const rpn: Token[] = [numberToken("5"), unaryToken("-")];
const rootNode = ast.Add(rpn);
expect(rootNode.value).toBe("-");
expect(rootNode.right?.value).toBe("5");
});
// Test for Collapse method (evaluating the AST)
it("should correctly evaluate AST for binary addition", () => {
const rpn: Token[] = [numberToken("3"), numberToken("4"), binaryToken("+")];
const rootNode = ast.Add(rpn);
const result = ast.Collapse(rootNode);
expect(result).toBe("7");
});
it("should correctly evaluate AST for unary minus", () => {
const rpn: Token[] = [numberToken("5"), unaryToken("-")];
const rootNode = ast.Add(rpn);
const result = ast.Collapse(rootNode);
expect(result).toBe("-5");
});
});