-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreter.ts
96 lines (83 loc) · 2.73 KB
/
interpreter.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* **Interpreter**
*
* > "Given a language, define a representation for its grammar along with an
* interpreter that uses the representation to interpret sentences in the language."
*
* Perhaps on of the odder birds in Design Patterns. Certainly
* not something I have been using a lot, if that matters.
*
* This pattern is meant to be used for cases where relatively simple
* language terms should be evaluated as expressions. It does not
* replace things like regular expressions, but is rather meant
* as a possibility when constructing, for example, domain specific languages.
*
* In my reading and studying the Design Patterns book, this one
* has been one of the more interesting ones, maybe because it seems
* relatively unmentioned. For more exercise, ask ChatGPT for examples
* that involve a DSL use case!
*
* We'll look at a basic math (arithmetic) processor here.
*
* @see https://en.wikipedia.org/wiki/Interpreter_pattern
* @see Page 243 in `Design Patterns - Elements of Reusable Object-Oriented Software`
*/
function interpreterDemo() {
// Globally known to the interpreter
class Context {
private variables: { [key: string]: number } = {};
setVariable(name: string, value: number) {
this.variables[name] = value;
}
getVariable(name: string) {
return this.variables[name];
}
}
// The abstraction all expressions have in common
abstract class Expression {
abstract interpret(context: Context): number;
}
// "Terminal expression" for numbers
class NumberExpression extends Expression {
constructor(private value: number) {
super();
}
interpret() {
return this.value;
}
}
// "Non-terminal expression" for addition
class AddExpression extends Expression {
constructor(private left: Expression, private right: Expression) {
super();
}
interpret(context: Context) {
return this.left.interpret(context) + this.right.interpret(context);
}
}
// "Non-terminal expression" for subtraction
class SubtractExpression extends Expression {
constructor(private left: Expression, private right: Expression) {
super();
}
interpret(context: Context) {
return this.left.interpret(context) - this.right.interpret(context);
}
}
// Let's interpret some expressions
const context = new Context();
context.setVariable('a', 10);
context.setVariable('b', 5);
const expression = new SubtractExpression(
// 10 + 7...
new AddExpression(
new NumberExpression(context.getVariable('a')),
new NumberExpression(7)
),
// ... -5
new NumberExpression(context.getVariable('b'))
);
const result = expression.interpret(context);
console.log(`Result: ${result}`);
}
interpreterDemo();