← All Exercises
Parse Arithmetic with Precedence
advancedjavascript
Background
Lexers and parsers are the core of language tooling. Implementing precedence climbing makes grammar rules executable instead of aspirational.
Problem
Parse an arithmetic expression of numbers, +, * and parentheses into an AST honouring precedence, then evaluate it.
Input
JSON object: { expression: string }Output
JSON object: { ast, value }Sample tests
Sample 1
Input: {"expression":"1+2*3"}Expected: {"ast":{"op":"+","left":{"value":1},"right":{"op":"*","left":{"value":2},"right":{"value":3}}},"value":7}Sample 2
Input: {"expression":"(1+2)*3"}Expected: {"ast":{"op":"*","left":{"op":"+","left":{"value":1},"right":{"value":2}},"right":{"value":3}},"value":9}Your solution
Learning objective
Implement a precedence-correct parser from scratch.