-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpnEvaluator.ts
56 lines (46 loc) · 1.28 KB
/
rpnEvaluator.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
import {
Binary,
NumericLiteral,
Operation,
Token,
TokenType,
UnaryOperation,
} from "./Types";
import {
binaryOperations,
isBinaryOperation,
isNumericalLiteral,
isUnaryOperation,
unaryOperations,
} from "./Utils";
// Reverse Polish Notation Evaluator
export function rpnEvaluator(rps: Token[]): NumericLiteral {
if (rps.length === 0) return "0";
let stack: string[] = [];
let acc = "";
for (let i = 0; i < rps.length; i++) {
const token = rps[i];
if (token.type === TokenType.Number) {
stack.push(token.value);
} else {
if (isBinaryOperation(token)) {
let right = stack.pop() as NumericLiteral;
let left = stack.pop() as NumericLiteral;
let operation = token.value as Binary;
acc = binaryOperations[operation](left, right);
stack.push(acc);
} else if (isUnaryOperation(token)) {
let operand = stack.pop() as NumericLiteral;
let operation = token.value as UnaryOperation;
let acc = unaryOperations[operation](operand);
stack.push(acc);
}
acc = "";
}
}
return stack.length === 1
? (stack[0] as NumericLiteral)
: (unaryOperations[rps[rps.length - 1].value as UnaryOperation](
stack[1] as NumericLiteral
) as NumericLiteral);
}