Skip to main content
πŸ”€ Parsers & Mini-Interpreters

What you're building

A function evaluate(expr) that takes a string like "3 + 4 * 2" and returns the correct numeric result (11), respecting standard operator precedence (* and / bind tighter than + and -).

This is the classic recursive-descent parser problem β€” the same technique used in every programming language compiler, spreadsheet engine, and formula field.

Requirements

  • Accept non-negative integers and the four operators: +, -, *, /
  • Respect standard precedence: * / / before + / -
  • Handle optional spaces between tokens
  • Integer division rounds toward zero (use Math.trunc)
  • Return a number (not a string)

Stretch goals

  • Support parentheses: "(2 + 3) * 4" β†’ 20
  • Support unary minus: "-3 + 5" β†’ 2
  • Return a descriptive error for invalid input

What this proves

  • You can implement a multi-precedence recursive parser without a library
  • You understand tokenisation, grammar, and evaluation order
  • Compilers/interpreters are no longer magic to you
⚑ 60 XP
solution.jsRuns in your browser
Loading editor…
Tests4 to pass
simple addition
precedence: multiply before add
left-to-right same precedence
mixed operators no spaces

Run your code to check these.