javascript 51 lines · 8 steps

Building a recursive descent calculator

A recursive descent parser evaluates arithmetic expressions while respecting operator precedence and parentheses.

Explained by highlit
1function evaluate(expression) {
2 const tokens = tokenize(expression);
3 let pos = 0;
4 
5 const peek = () => tokens[pos];
6 const next = () => tokens[pos++];
7 
8 function parseExpression() {
9 let value = parseTerm();
10 while (peek() === '+' || peek() === '-') {
11 const op = next();
12 const rhs = parseTerm();
13 value = op === '+' ? value + rhs : value - rhs;
14 }
15 return value;
16 }
17 
18 function parseTerm() {
19 let value = parseFactor();
20 while (peek() === '*' || peek() === '/') {
21 const op = next();
22 const rhs = parseFactor();
23 value = op === '*' ? value * rhs : value / rhs;
24 }
25 return value;
26 }
27 
28 function parseFactor() {
29 if (peek() === '(') {
30 next();
31 const value = parseExpression();
32 if (next() !== ')') throw new Error('Expected closing parenthesis');
33 return value;
34 }
35 const token = next();
36 if (token === undefined || isNaN(Number(token))) {
37 throw new Error(`Unexpected token: ${token}`);
38 }
39 return Number(token);
40 }
41 
42 const result = parseExpression();
43 if (pos !== tokens.length) throw new Error(`Unexpected token: ${peek()}`);
44 return result;
45}
46 
47function tokenize(input) {
48 const matches = input.match(/\d+(?:\.\d+)?|[+\-*/()]/g);
49 if (!matches) throw new Error('Empty expression');
50 return matches;
51}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Separating parsing into precedence levels lets grammar structure enforce math order naturally.
  2. 2A shared cursor plus peek/next helpers keeps mutually recursive parse functions in sync.
  3. 3Recursion mirrors nested grammar rules, so parentheses fall out for free by re-entering the top level.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a recursive descent calculator — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code