Recursive-Descent Calculator
Hard · Parsing
Write calculate(source) that evaluates an expression with non-negative integers, spaces, + - * /, parentheses and unary minus. * and / bind tighter than + and -, same-level operators go left to right, and / truncates toward zero.
Suggested grammar:
expr = term (("+" | "-") term)*
term = factor (("*" | "/") factor)*
factor = number | "(" expr ")" | "-" factor
Return { ok: true, value }, or { ok: false, error } with one of these messages (indexes are 0-based):
- Unexpected character at <index> for a character that is not a digit, space, operator or parenthesis (checked first).
- Syntax error at <index> for the first token the parser cannot use (including leftovers). If the input ends too early, the index is source.length.
- Division by zero if the expression is valid but divides by zero.
Next: Mini Template Engine