Skip to content

Instantly share code, notes, and snippets.

@bakso
Created July 25, 2016 02:22
Show Gist options
  • Save bakso/dbb1b7a9a7b801ed83317d9c1a812240 to your computer and use it in GitHub Desktop.
Save bakso/dbb1b7a9a7b801ed83317d9c1a812240 to your computer and use it in GitHub Desktop.
Caculator modified from pegjs online example
Expression
= head:Term tail:(_ ("+" / "-") _ Term)* {
var result = head, i;
for (i = 0; i < tail.length; i++) {
if (tail[i][1] === "+") { result += tail[i][3]; }
if (tail[i][1] === "-") { result -= tail[i][3]; }
}
return result;
}
Term
= head:Factor tail:(_ ("*" / "/") _ Factor)* {
var result = head, i;
for (i = 0; i < tail.length; i++) {
if (tail[i][1] === "*") { result *= tail[i][3]; }
if (tail[i][1] === "/") { result /= tail[i][3]; }
}
return result;
}
Factor
= neg:NegId number:Factor_NUM { if (neg === "-") { return -number} return number }
Factor_NUM
= "(" _ expr:Expression _ ")" { return expr; }
/ Integer
Integer "integer"
= [0-9]+ { return parseInt(text(), 10); }
NegId
= [\-+]? { return text()}
_ "whitespace"
= [ \t\n\r]*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment