Skip to content

Instantly share code, notes, and snippets.

@tlrobinson
Forked from 140bytes/LICENSE.txt
Created October 3, 2011 16:13
Show Gist options
  • Save tlrobinson/1259487 to your computer and use it in GitHub Desktop.
Save tlrobinson/1259487 to your computer and use it in GitHub Desktop.
Prefix notation calculator parser

Prefix notation calculator parser

This is a very simple prefix notation calculator implementation in JavaScript, for the purpose of demonstrating a simple lexer, parser, compiler, and interpreter for my JSConf.eu talk, "JavaScript Compilers for Fun and Profit".

They're available packaged together here:

mini-calc-golfed.js contains each component JS-golfed down to < 140 bytes.

And individually as 140byt.es forks here:

function(tokens) {
var nodes = [];
tokens.shift();
while (token = tokens.shift()) {
if (token == "(") {
// unget the paren and recurse
tokens.unshift(token);
nodes.push(parse(tokens));
} else if (token == ")") {
return nodes;
} else {
nodes.push(token);
}
}
}
function p(a,b,c){c=[];a.shift();while(b=a.shift()){if(b=="("){a.unshift(b);c.push(p(a))}else if(b==")"){return c}else{c.push(b)}}}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Tom Robinson <http://tlrobinson.net/>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "theNameOfYourLibWhichMustBeAValidCamelCasedJavaScriptIdentifier",
"description": "This should be a short description of your entry.",
"keywords": [
"five",
"descriptive",
"keywords",
"or",
"fewer"
]
}
<!DOCTYPE html>
<title>Prefix notation calculator parser</title>
<script>
function repl(c,t,h,r){h=[t||""];while(s=prompt(h.slice(-10).join("\n"))){try{r=(c||eval)(s)}catch(e){r=e}h.push(""+r)}}
// lexer
function l(s){return s.match(/\(|\)|\d+(\.\d+)?|\w+|[+*\/-]/g).map(function(t){return /^\d/.test(t)?parseFloat(t):t})}
// parser
function p(a,b,c){c=[];a.shift();while(b=a.shift()){if(b=="("){a.unshift(b);c.push(p(a))}else if(b==")"){return c}else{c.push(b)}}}
repl(function(s) { return JSON.stringify(p(l(s))); }, "Prefix notation calculator parser, e.x. '(+ 1 (* 2 3))'")
</script>
@tsaniel
Copy link

tsaniel commented Oct 5, 2011

Not sure if functional
function p(a,b,c){for(a.shift(c=[]);b=a.shift();)if(b=="(")a.unshift(b),c.push(p(a));else if(b==")")return c;else c.push(b);}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment