|
|
@ -4,23 +4,23 @@
|
|
|
|
// Accepts expressions like "2 * (3 + 4)" and computes their value.
|
|
|
|
// Accepts expressions like "2 * (3 + 4)" and computes their value.
|
|
|
|
|
|
|
|
|
|
|
|
Expression
|
|
|
|
Expression
|
|
|
|
= head:Term tail:(_ ("+" / "-") _ Term)* {
|
|
|
|
= head:Term tail:(_ @("+" / "-") _ @Term)* {
|
|
|
|
return tail.reduce(function(result, element) {
|
|
|
|
return tail.reduce(function(result, [operator, factor]) {
|
|
|
|
if (element[1] === "+") { return result + element[3]; }
|
|
|
|
if (operator === "+") return result + factor;
|
|
|
|
if (element[1] === "-") { return result - element[3]; }
|
|
|
|
if (operator === "-") return result - factor;
|
|
|
|
}, head);
|
|
|
|
}, head);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
Term
|
|
|
|
Term
|
|
|
|
= head:Factor tail:(_ ("*" / "/") _ Factor)* {
|
|
|
|
= head:Factor tail:(_ @("*" / "/") _ @Factor)* {
|
|
|
|
return tail.reduce(function(result, element) {
|
|
|
|
return tail.reduce(function(result, [operator, factor]) {
|
|
|
|
if (element[1] === "*") { return result * element[3]; }
|
|
|
|
if (operator === "*") return result * factor;
|
|
|
|
if (element[1] === "/") { return result / element[3]; }
|
|
|
|
if (operator === "/") return result / factor;
|
|
|
|
}, head);
|
|
|
|
}, head);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
Factor
|
|
|
|
Factor
|
|
|
|
= "(" _ expr:Expression _ ")" { return expr; }
|
|
|
|
= "(" _ @Expression _ ")"
|
|
|
|
/ Integer
|
|
|
|
/ Integer
|
|
|
|
|
|
|
|
|
|
|
|
Integer "integer"
|
|
|
|
Integer "integer"
|
|
|
|