-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathParser.ts
47 lines (32 loc) · 1.36 KB
/
Parser.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
import { Expression, NumberExpression, AdditionExpression, SubtractionExpression } from "./Interpreters"
export class Parser {
expressions: Expression[] = []
parse(input: string): number {
try {
let symbols = input.split(" ")
symbols.forEach((symbol: string) => {
if(symbol.match(/[0-9]+$/)) this.expressions.push(new NumberExpression(symbol))
else if(symbol.match(/[+-]+$/)) {
let expression1 = this.expressions.pop() || new NumberExpression("0")
let expression2 = this.expressions.pop() || new NumberExpression("0")
let result = 0
switch(symbol) {
case "+":
result = new AdditionExpression(expression1, expression2).interpret()
break
case "-":
result = new SubtractionExpression(expression1, expression2).interpret()
break
}
this.expressions.push(new NumberExpression(result.toString()))
}
})
return this.expressions.pop()?.interpret() || 0
}
catch(err) {
console.log(err)
console.log("invalid input")
return 0
}
}
}