Click here to Skip to main content
15,880,543 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 228.3K   2.9K   98  
Introduction to the compiling/interpreting process by making a simple calculator application in JavaScript
var lex = function (input) {
	var isOperator = function (c) { return /[+\-*\/\^%=(),]/.test(c); },
		isDigit = function (c) { return /[0-9]/.test(c); },
		isWhiteSpace = function (c) { return /\s/.test(c); },
		isIdentifier = function (c) { return typeof c === "string" && !isOperator(c) && !isDigit(c) && !isWhiteSpace(c); };

	var tokens = [], c, i = 0;
	var advance = function () { return c = input[++i]; };
	var addToken = function (type, value) {
		tokens.push({
			type: type,
			value: value
		});
	};
	while (i < input.length) {
		c = input[i];
		if (isWhiteSpace(c)) advance();
		else if (isOperator(c)) {
			addToken(c);
			advance();
		}
		else if (isDigit(c)) {
			var num = c;
			while (isDigit(advance())) num += c;
			if (c === ".") {
				do num += c; while (isDigit(advance()));
			}
			num = parseFloat(num);
			if (!isFinite(num)) throw "Number is too large or too small for a 64-bit double.";
			addToken("number", num);
		}
		else if (isIdentifier(c)) {
			var idn = c;
			while (isIdentifier(advance())) idn += c;
			addToken("identifier", idn);
		}
		else throw "Unrecognized token.";
	}
	addToken("(end)");
	return tokens;
};

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