HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Create a math expression parser in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptexpressionparsercreatemath

Problem

In previous articles, we've explored how to tokenize math expressions and parsing using Abstract Syntax Trees. This time around, we're revisiting math expressions, to build a robust parsing and evaluation system combining the two techniques, and more.
A context-free grammar (CFG) is a set of rules that define the structure of a language. It consists of a set of terminal symbols, non-terminal symbols, a start symbol, and a set of production rules. The production rules define how the non-terminal symbols can be replaced by a sequence of terminal and non-terminal symbols.
Let's look at an example of a simple CFG, representing basic arithmetic expressions:
| Rule | Production |
|------|------------|

Solution

Having these two classes, we can now **define symbols and rules**, like so:


Let's look at an example of a simple CFG, representing basic arithmetic expressions:
| Rule | Production |
|------|------------|
| P | S |
| S | S + M |
| S | M |

Code Snippets

Having these two classes, we can now **define symbols and rules**, like so:
Notice how **literal tokens** like `+` and `*` need to be defined as their own symbols and are represented as **strings**. Similarly, **numeric values** are represented as **regular expressions**. This allows us to tokenize the input string and match tokens against the rules, as we'll see shortly.

### Context-free grammar

Given a set of rules, we can now define a context-free grammar (CFG) class to hold the rules and provide methods for working with them. We'll extract the rules, symbols and **token matchers** when creating the CFG to make them easily accessible.
We can now create a CFG instance with the rules we defined earlier:

Context

From 30-seconds-of-code: math-expression-parser

Revisions (0)

No revisions yet.