-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidateMath.js
More file actions
133 lines (94 loc) · 2.83 KB
/
validateMath.js
File metadata and controls
133 lines (94 loc) · 2.83 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
function getMathStatus(math) {
const constants = ["pi", "e", "sqrt2", "In2", "In10"];
const functions = ["sin", "cos", "tg", "ctg", "tan", "cot", "sinh", "cosh", "th", "cth"];
const operators = ["*", "/", "-", "+"];
const leftParenthesis = "(";
const rightParenthesis = ")";
let tokens = new Array();
let i = 0;
const len = math.length;
//проверка на цифры и латинские буквы
function isLetter(c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
function isDigit(c) {
return c >= '0' && c <= '9';
}
//проверка на перменную
function isVarChar(c) {
return isLetter(c) || isDigit(c) || c === '_';
}
while (i < len) {
let c = math[i];
//пропуск пробелов
if (c === ' ') {
i++;
continue;
}
//операторы
if (operators.includes(c)) {
tokens.push({ type: "operator", span: [i, i+1] });
i++;
continue;
}
//скобки ()
if (c === leftParenthesis) {
tokens.push({ type: "left_parenthesis", span: [i, i+1] });
i++;
continue;
}
if (c === rightParenthesis) {
tokens.push({ type: "right_parenthesis", span: [i, i+1] });
i++;
continue;
}
//число (integer or float, без знака, с точкой)
if (isDigit(c) || c === '.') {
let start = i;
let dotCount = 0;
if (c === '.') dotCount = 1;
i++;
while (i < len) {
let ch = math[i];
if (isDigit(ch)) {
i++;
}
else if (ch === '.') {
if (dotCount === 1) break; //больше одной точки нельзя
dotCount++;
i++;
}
else {
break;
}
}
tokens.push({ type: "number", span: [start, i] });
continue;
}
//константа или функция или переменная (начинается с буквы)
if (isLetter(c)) {
let start = i;
i++;
while (i < len && isVarChar(math[i])) {
i++;
}
let word = math.slice(start, i);
//проверим константу (чувствительна к регистру, поэтому exact)
if (constants.includes(word)) {
tokens.push({ type: "constant", span: [start, i] });
continue;
}
//проверим функцию
if (functions.includes(word)) {
tokens.push({ type: "function", span: [start, i] });
continue;
}
//иначе переменная
tokens.push({ type: "variable", span: [start, i] });
continue;
}
//если не попали ни в одно условие - просто сдвинем индекс, чтобы избежать зацикливания
i++;
}
return tokens;
}