Click here to Skip to main content
12,350,723 members (25,235 online)
Click here to Skip to main content

Stats

112.8K views
1.8K downloads
94 bookmarked
Posted

How to write a simple interpreter in JavaScript

, 30 Oct 2014 CPOL
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)

Share

About the Author

Peter_Olson
United States United States
I am active on Stack Overflow.

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

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160621.1 | Last Updated 30 Oct 2014
Article Copyright 2012 by Peter_Olson
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid