-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenize.ts
120 lines (106 loc) · 2.48 KB
/
tokenize.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
export interface Token {
type: "number" | "operator" | "parenthesis";
value: string;
}
export default function tokenize(expression: string): Token[] {
const tokens: Token[] = [];
let currentToken = "";
let expectNegative = true;
for (let i = 0; i < expression.length; ++i) {
const char = expression[i];
switch (char) {
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
case "0":
case ".":
currentToken += char;
expectNegative = false;
break;
case "+":
case "*":
case "/":
expectNegative = true;
if (currentToken) {
tokens.push({
type: "number",
value: currentToken,
});
}
tokens.push({
type: "operator",
value: char,
});
currentToken = "";
break;
case "-": {
// this token has 2 meanings, it can be a subtraction operator or a negative number
// if the previous token is a number, it's a subtraction operator
if (expectNegative) {
// it's a negative number
currentToken = char;
expectNegative = false;
} else {
// meaning there are digits before the -
// it's a subtraction operator
if (currentToken) {
tokens.push({
type: "number",
value: currentToken,
});
}
tokens.push({
type: "operator",
value: char,
});
currentToken = "";
// subtracting a negative number is allowed
expectNegative = true;
}
break;
}
case "(":
expectNegative = true;
tokens.push({
type: "parenthesis",
value: char,
});
currentToken = "";
break;
case ")": {
expectNegative = false;
if (currentToken) {
tokens.push({
type: "number",
value: currentToken,
});
currentToken = "";
}
tokens.push({
type: "parenthesis",
value: char,
});
break;
}
case " ":
// break switch
break;
default:
throw new Error("Invalid character");
}
}
// Push the last token
if (currentToken) {
tokens.push({
type: "number",
value: currentToken,
});
}
return tokens;
}