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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Separating parsing into precedence levels lets grammar structure enforce math order naturally.
- 2A shared cursor plus peek/next helpers keeps mutually recursive parse functions in sync.
- 3Recursion mirrors nested grammar rules, so parentheses fall out for free by re-entering the top level.
Related explainers
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
python
from typing import Any, Sequence, Mapping def render_markdown_table(
Rendering an aligned Markdown table in Python
string formatting
data transformation
closures
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-recursive-descent-calculator-explained-javascript-07b3/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.