Click here to Skip to main content
15,892,927 members
Articles / Web Development / HTML

How to Write a Simple Interpreter in JavaScript

Rate me:
Please Sign up or sign in to vote.
4.88/5 (55 votes)
30 Oct 2014CPOL10 min read 229.7K   2.9K   98  
Introduction to the compiling/interpreting process by making a simple calculator application in JavaScript
<!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 Service 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)


Written By
United States United States
I am active on Stack Overflow.

You can contact me via email at peter.e.c.olson+codeproject@gmail.com

Comments and Discussions