Skip to content

Instantly share code, notes, and snippets.

@tlrobinson
Forked from 140bytes/LICENSE.txt
Created October 3, 2011 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlrobinson/1259461 to your computer and use it in GitHub Desktop.
Save tlrobinson/1259461 to your computer and use it in GitHub Desktop.
Prefix notation calculator lexer

Prefix notation calculator lexer

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(string) {
// use a regular expression to split the input string into tokens
var tokens = string.match(/\(|\)|\d+(\.\d+)?|\w+|[+*\/-]/g);
return tokens.map(function(token) {
// convert the numbers tokens
return /^\d/.test(token) ? parseFloat(token) : token;
});
}
function l(s){return s.match(/\(|\)|\d+(\.\d+)?|\w+|[+*\/-]/g).map(function(t){return /^\d/.test(t)?parseFloat(t):t})}
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 lexer</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})}
repl(function(s) { return JSON.stringify(l(s)); }, "Prefix notation calculator lexer, e.x. '(+ 1 (* 2 3))'")
</script>
@tsaniel
Copy link

tsaniel commented Oct 5, 2011

Reuse the original function.
function l(s,a){return a>-1?s.match(/\(|\)|\d+(\.\d+)?|\w+|[+*\/-]/g).map(l):/^\d/.test(s)?parseFloat(s):s}

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