-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluator.js
50 lines (40 loc) · 1.14 KB
/
evaluator.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
var Parser = require('./parser.js');
module.exports = function Evaluator() {
var parser = new Parser();
function evaluateOperation(node) {
switch (node.operation) {
case '+':
if (node.left) {
return evaluateNode(node.left) + evaluateNode(node.right);
}
return evaluateNode(node.right);
case '-':
if (node.left) {
return evaluateNode(node.left) - evaluateNode(node.right);
}
return evaluateNode(node.right) * - 1;
case '*':
return evaluateNode(node.left) * evaluateNode(node.right);
case '/':
return evaluateNode(node.left) / evaluateNode(node.right);
default:
parser.throw('Unknown operation ' + node.operation);
}
}
function evaluateNode(node) {
if (node.operation) {
return evaluateOperation(node);
}
if (node.type === 'NUMBER') {
return node.value
}
parser.throw('Unhandled node\n' + JSON.stringify(node, null, 2));
}
this.evaluate = function (input) {
var tree = parser.parse(input);
if (tree === null) {
return '';
}
return evaluateNode(tree);
};
};