-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpolish.js
More file actions
53 lines (45 loc) · 1.15 KB
/
polish.js
File metadata and controls
53 lines (45 loc) · 1.15 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
const TokenType = require('./token-type');
const PolishNotation = tokens => {
const queue = [];
const stack = [];
tokens.forEach(token => {
switch (token.type) {
case TokenType.LITERAL:
queue.unshift(token);
break;
case TokenType.BINARY_AND:
case TokenType.BINARY_OR:
case TokenType.OP_NOT:
case TokenType.PAR_OPEN:
stack.push(token);
break;
case TokenType.PAR_CLOSE:
while (
stack.length &&
stack[stack.length - 1].type !== TokenType.PAR_OPEN
) {
queue.unshift(stack.pop());
}
stack.pop();
if (stack.length && stack[stack.length - 1].type === TokenType.OP_NOT) {
queue.unshift(stack.pop());
}
break;
default:
break;
}
});
const result = (stack.length && [...stack.reverse(), ...queue]) || queue;
return result;
};
// 波兰列表生成器
const PolishGenerator = function*(polish) {
for (let index = 0; index < polish.length - 1; index++) {
yield polish[index];
}
return polish[polish.length - 1];
};
module.exports = {
PolishNotation,
PolishGenerator
};