-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmachine.js
64 lines (49 loc) · 1.24 KB
/
machine.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
var ops = require('./operations.js').ops;
var operands = [];
var values = [];
function removeEndTokens() {
var index;
while((index = values.indexOf("end")) != -1) {
values.splice(index, 1);
}
}
function popUntilEnd() {
var res = [], val;
while((val = values.pop()) != undefined && val != "end") {
res.push(val);
}
return res;
}
function callOp(op) {
if (op.args == -1) {
return op.func(popUntilEnd());
} else if (op.args == 1) {
return op.func(values.pop());
} else if (op.args == 2) {
return op.func(values.pop(), values.pop());
}
}
function parse(operation) {
if (operation == "")
return null;
operands = operation.split("/");
values = [];
var operand;
while (operand = operands.pop()) {
console.log("[" + values + "] << " + operand);
if (operand.match(/^\d+$/) != undefined) {
values.push(parseInt(operand));
} else if (operand == "end") {
values.push(operand);
} else if (ops[operand] != undefined) {
var value = callOp(ops[operand]);
values.push(value);
} else {
console.log("ERROR: Unrecognized operand: " + operand);
}
}
removeEndTokens();
console.log("[" + values + "]");
return values.reverse();
};
exports.parse = parse;