-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrpn.js
More file actions
69 lines (64 loc) · 1.49 KB
/
Copy pathrpn.js
File metadata and controls
69 lines (64 loc) · 1.49 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
'use strict';
const binOps = '+ - / % & | ^ << >> > >= < <= == != && ||'
.split(/\s+/)
.reduce((res, e) => {
res[e] = e;
return res;
}, {
'u*': '*'
});
const signedBinOps = {
'*': '*'
};
const unOps = {
'!': '!',
'~': '~'
};
const rpn = (seq, arr) => {
if (typeof seq === 'string') {
seq = seq.split(/\s+/);
}
// if (typeof arr === 'string') {
// arr = arr.split(/\s+/);
// }
arr = arr.map(e => e.name);
for (let j = 0; j < 100; j++) {
for (let i = 0; i < seq.length; i++) {
const cmd = seq[i];
if (unOps[cmd]) {
arr.push(cmd + arr.pop());
} else
if (signedBinOps[cmd]) {
const rhs = arr.pop();
const lhs = arr.pop();
arr.push(`($signed(${lhs}) ${signedBinOps[cmd]} $signed(${rhs}))`);
} else
if (binOps[cmd]) {
const rhs = arr.pop();
const lhs = arr.pop();
arr.push(`(${lhs} ${binOps[cmd]} ${rhs})`);
} else
if (cmd.slice(0, -1) === '(' && binOps[cmd.slice(1)]) {
const lhs = arr.shift();
const rhs = arr.shift();
arr.unshift(`(${lhs} ${cmd.slice(1)} ${rhs})`);
} else
if (cmd === 'swap') {
const rhs = arr.pop();
const lhs = arr.pop();
arr.push(rhs);
arr.push(lhs);
} else {
const num = Number(cmd);
if (!isNaN(num)) {
arr.push(num);
}
}
if (arr.length < 2) {
return arr[0];
}
}
}
return arr[0];
};
module.exports = rpn;