HardPro challengeTypeScript

Interpreter

TypeScriptDesign PatternsBehavioralInterpreter

Represent a grammar as a tree of expression objects, each of which knows how to evaluate itself — a minimal calculator for "3 + 4 - 2"-style expressions, evaluated strictly left to right.

Implement `NumberExpression.interpret()` (returns its literal value) and AddExpression/SubtractExpression.interpret() (combine their left/right sub-expressions).

solve(expr) parses a space-separated "<num> (+|-) <num> ..." string into a tree via parse (already wired) and evaluates it.

solve('10 - 5 - 2')3 (left to right: (10 - 5) - 2).

Sample tests

Test #1Mixed add/subtract
Input: ["3 + 4 - 2"]
Output: 5
Test #2Left-to-right subtraction
Input: ["10 - 5 - 2"]
Output: 3
Test #3A single number, no operators
Input: ["7"]
Output: 7