-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmsg.js
50 lines (50 loc) · 2 KB
/
msg.js
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
module.exports = {
parseMsg(msg) {
// Разбор сообщения
if (msg.endsWith('\u0000'))
// Удаление символа в конце
msg = msg.substring(0, msg.length - '\u0000'.length);
// Разбор сообщения
let array = msg.match(/(\(|[-\d.]+|[\\"\w]+|\))/g);
let res = {msg, p: []}; // Результирующее сообщение
// Анализировать с индекса 0, результат в res
this.parse(array, {idx: 0}, res);
this.makeCmd(res); // Выделить команду
return res;
},
parse(array, index, res) {
// Разбор сообщения в скобках
// Всегда с открывающей скобки
if (array[index.idx] !== '(') return;
index.idx++;
// Разбор внутри скобок
this.parseInner(array, index, res);
},
parseInner(array, index, res) {
// Пока не встретится закрывающая скобка
while (array[index.idx] !== ')') {
// Если внутри еще одна скобка
if (array[index.idx] === '(') {
let r = {p: []};
// Рекурсивный вызов с index
this.parse(array, index, r);
res.p.push(r);
} else {
// Одиночный параметр
let num = parseFloat(array[index.idx]);
res.p.push(isNaN(num) ? array[index.idx] : num);
index.idx++;
}
}
index.idx++;
},
makeCmd(res) {
// Выделение команды
if (res.p && res.p.length > 0) {
// Первый параметр — команда
res.cmd = res.p.shift();
// Выделить команды у параметров
for (let value of res.p) this.makeCmd(value);
}
},
};