Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Build a math expression evaluator in JavaScript

122 a four-operator expression evaluator

hard

Evaluate arithmetic from a string: + - * /, parentheses, decimals and unary minus, with multiplication binding tighter than addition. Tokenise with one regular expression, then write recursive descent — expr calls term calls primary, and primary calls back into expr for a bracket. Report a useful message on malformed input, including trailing junk.

Stuck? Three hints, smallest first
  1. 1. One match with alternation gives the tokens: a number, an operator or a parenthesis, or any single non-space character so bad input is visible rather than skipped.
  2. 2. Precedence is the nesting of the functions. expr loops over + - and each side is a term; term loops over * / and each side is a primary.
  3. 3. Keep the position in a closed-over at, with peek() and eat(token). After the top-level call, check that every token was consumed.

The answer

const tokenise = (text) => text.match(/\d+(?:\.\d+)?|[-+*/()]|\S/g) ?? [];

const evaluate = (text) => {
  const tokens = tokenise(text);
  let at = 0;
  const peek = () => tokens[at];
  const eat = (want) => {
    if (peek() !== want) throw new SyntaxError(`expected ${want}, found ${peek() ?? 'end of input'}`);
    at += 1;
  };
  const primary = () => {
    const token = peek();
    if (token === '(') {
      eat('(');
      const inner = expr();
      eat(')');
      return inner;
    }
    if (token === '-') { eat('-'); return -primary(); }
    if (token !== undefined && /^\d/.test(token)) { at += 1; return Number(token); }
    throw new SyntaxError(`unexpected ${token ?? 'end of input'}`);
  };
  const term = () => {
    let left = primary();
    while (peek() === '*' || peek() === '/') {
      const op = peek();
      at += 1;
      const right = primary();
      left = op === '*' ? left * right : left / right;
    }
    return left;
  };
  const expr = () => {
    let left = term();
    while (peek() === '+' || peek() === '-') {
      const op = peek();
      at += 1;
      const right = term();
      left = op === '+' ? left + right : left - right;
    }
    return left;
  };
  const value = expr();
  if (at !== tokens.length) throw new SyntaxError(`trailing ${peek()}`);
  return value;
};

const complain = (text) => {
  try { return evaluate(text); } catch (e) { return e.message; }
};

console.log('tokens :', tokenise('1500 * (12 - 2)'));
console.log('fare   :', evaluate('1500 * 12 + 500'));
console.log('errors :', ['(2 + 3', '2 +', '2 3', '4 % 2'].map(complain));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('multiplication binds tighter than addition', evaluate('2 + 3 * 4'), 14);
test('brackets override that, because primary re-enters expr', evaluate('(2 + 3) * 4'), 20);
test('subtraction is left associative, which the loop gives for free', evaluate('10 - 3 - 2'), 5);
test('unary minus works in front of a number and of a bracket', [evaluate('-4 + 10'), evaluate('3 * -(1 + 1)')], [6, -6]);
test('decimals and division come out as ordinary numbers', evaluate('7 / 2'), 3.5);
test('so a fare of 12km at 1500 plus a 500 pickup is one expression', evaluate('1500 * 12 + 500'), 18500);
test('an unclosed bracket names the token it wanted', complain('(2 + 3'), 'expected ), found end of input');
test('an operator with nothing after it is caught in primary', complain('2 +'), 'unexpected end of input');
test('and input that parsed but did not finish is rejected, not silently truncated', [complain('2 3'), complain('4 % 2')], ['trailing 3', 'trailing %']);

Recursive descent is the parsing technique worth knowing by hand, because the grammar and the code are the same shape. One function per precedence level, each looping over its own operators and calling the tighter level for its operands. Left associativity falls out of the loop; had expr called itself recursively for the right side instead, 10 - 3 - 2 would come out as 9.

The tokeniser's last alternative, \S, is the one that earns its place. Without it a stray % would simply vanish and 4 % 2 would quietly evaluate to 4. Making unknown characters into tokens means the parser sees them and can complain.

The final check — that at reached the end — is the difference between a parser and a prefix-reader. expr is perfectly happy to stop early, so without that line '2 3' returns 2 and a typo becomes a wrong number rather than an error. Note also what this evaluator deliberately does not do: no eval, no new Function, so a string from a user cannot run code.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.