Drill

ProblemsTypeScript › text

Evaluate a formula

hardtextTypeScript

A spreadsheet cell holds a small arithmetic formula, and the recalculation pass turns it into a number.

evaluateExpression(text: string) → int

Solve it in the editor →

Where you start

function evaluateExpression(text: string): number {
  
}

Worked examples

CallResult
evaluateExpression("2+3*4")14
evaluateExpression("10-2-3")5
evaluateExpression("7/2")3
evaluateExpression("2*3+4*5")26

Hint

Carry a running total plus one pending term. On + or - you bank the pending term; on * or / you fold the new number into it.

Reference solution in TypeScript
function evaluateExpression(text: string): number {
  let total = 0;
  let term = 0;
  let num = 0;
  let op = '+';
  const clean = text.replace(/\s+/g, '');
  for (let i = 0; i <= clean.length; i++) {
    const c = i < clean.length ? clean[i] : '#';
    if (c >= '0' && c <= '9') {
      num = num * 10 + (clean.charCodeAt(i) - 48);
      continue;
    }
    if (op === '+') {
      total += term;
      term = num;
    } else if (op === '-') {
      total += term;
      term = -num;
    } else if (op === '*') {
      term = term * num;
    } else {
      if (num === 0) return 0;
      term = Math.trunc(term / num);
    }
    op = c;
    num = 0;
  }
  return total + term;
}

The same problem in another language

More text problems in TypeScript