O'Reilly logo

Beautiful JavaScript by Anton Kovalyov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

CHAPTER SEVEN

Math Expression Parser and Evaluator

Domain-specific languages (DSLs) are encountered in many aspects of a software engineer’s life: configuration file formats, data transfer protocols, model schemas, application extensions, interface definition languages, and many others. Because of the nature of such languages, the language expression needs to be straightforward and easy to understand.

In this chapter, we will explore the use of JavaScript to implement a simple language that can be used to evaluate a mathematical expression. In a way, it is very similar to a classic handheld programming calculator. Besides the typical math syntax, our JavaScript code should handle operator precedence and understand predefined functions.

Given a math expression as a string, this is the series of processing applied to that string:

  • The string is split into a stream of tokens.

  • The tokens are used to construct the syntax tree.

  • The syntax tree is traversed to evaluate the expression.

Each step will be described in the following sections.

Lexical Analysis and Tokens

The first important thing to do to a string representing a math expression is lexical analysis—that is, splitting the string into a stream of tokens. Quite expectedly, a function that does this is often called a tokenizer. Alternatively, it is also known as a lexer or a scanner.

We first need to define the types of the tokens. Since we’ll be dealing with simple math expressions, all we really need are ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required