Click here to Skip to main content
Click here to Skip to main content

How to write a simple interpreter in JavaScript

By , 3 May 2012
 
<!DOCTYPE html>
<html>
<head>
	<title>Calculator</title>
</head>
<body>
Enter Calculations:<br>
<textarea id="input" rows="20" cols="50">
3
2 ^ 8
(12 % 7) * (3 + 2)
19 / -9

hoursPerDay = 24
minutesPerHour = 60
minutesPerDay = minutesPerHour * hoursPerDay
minutesPerDay
minutesPerDay * 60

toDegrees(radians) = radians * 180 / pi
toDegrees(2 * pi)

cylinderVolume(r, h) = pi * r ^ 2 * h
cylinderVolume(2, 4)
</textarea><br>
<button id="calculate">Calculate</button>
<pre id="output"></pre>
<script>
	if (!Object.create) {
		Object.create = function (o) {
			function F() { }
			F.prototype = o;
			return new F();
		};
	}
</script>
<script src="lexer.js"></script>
<script src="parser.js"></script>
<script src="evaluator.js"></script>
<script>
	var calculate = function (input) {
		try {
			var tokens = lex(input);
			var parseTree = parse(tokens);
			var output = evaluate(parseTree);
			return output;
		} catch (e) {
			return e;
		}
	};

	document.getElementById("calculate").onclick = function () {
		var input = document.getElementById("input").value;
		output = calculate(input);
		document.getElementById("output").innerHTML = output;
	};
</script>
</body>
</html>

By viewing downloads associated with this article you agree to the Terms of use and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Peter_Olson

United States United States
I'm an 18 year old web developer and I have been programming for about 3 years.
 
I am active on Stack Overflow.
 
You can contact me via email at peter.e.c.olson+codeproject@gmail.com

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 3 May 2012
Article Copyright 2012 by Peter_Olson
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid