1
Write your PEG.js grammar

x
1
// Simple Arithmetics Grammar
2
// ==========================
3
//
4
// Accepts expressions like "2 * (3 + 4)" and computes their value.
5
6
Expression
7
  = head:Term tail:(_ ("+" / "-") _ Term)* {
8
      return tail.reduce(function(result, element) {
9
        if (element[1] === "+") { return result + element[3]; }
10
        if (element[1] === "-") { return result - element[3]; }
11
      }, head);
12
    }
13
14
Term
15
  = head:Factor tail:(_ ("*" / "/") _ Factor)* {
16
      return tail.reduce(function(result, element) {
17
        if (element[1] === "*") { return result * element[3]; }
18
        if (element[1] === "/") { return result / element[3]; }
19
      }, head);
20
    }
21
22
Factor
23
  = "(" _ expr:Expression _ ")" { return expr; }
24
  / Integer
25
26
Integer "integer"
27
  = _ [0-9]+ { return parseInt(text(), 10); }
28
29
_ "whitespace"
30
  = [ \t\n\r]*
31
              
Parser built successfully.0.81 kB, 32 ms, 25 kB/s

2
Test the generated parser with some input

Input parsed successfully.0.011 kB, 1 ms, 11 kB/s

Output

14

3
Download the parser code