Scan the string once, left to right, keeping three things: the running total, the sign of the number being read, and the number itself, built digit by digit (num = num * 10 + digit) so multi-digit numbers work. On + or -, add sign * num to the total, reset the number and remember the new sign; after the loop add the last number. "No BODMAS" means operators are applied in the order they appear, so this single pass is the whole algorithm. "Handle all edge cases" is the real question: spaces, numbers with several digits, a leading minus, an empty string, two operators in a row, a trailing operator, letters, decimals, and division by zero if * and / are allowed. Decide for each whether it has a value or is an error, and say so. Don't use eval: it runs any code in the string.
Evaluate a basic arithmetic expression string like "1+3-2" and print the output. Handle all edge cases (no BODMAS required).
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
num grows as digits arrive. An operator means the number is finished: it goes into total with the sign that preceded it, and the operator becomes the sign for the next number. Starting with sign = 1 and num = 0 makes a leading minus work without a special case. Spaces are skipped because they match neither branch. The last check shows the cost of skipping everything unknown: 2*3 reads as 23 and 1.5+1 as 16, silently.
// One pass, left to right. Build the current number digit by digit; at each + or -, add the// finished number to the total with the sign that came before it.function evaluate(expr) {let total = 0;let sign = 1;let num = 0;for (const ch of expr) {if (ch >= '0' && ch <= '9') {num = num * 10 + Number(ch);} else if (ch === '+' || ch === '-') {total += sign * num;num = 0;sign = ch === '+' ? 1 : -1;}}return total + sign * num; // the last number has no operator after it}
passes 7 checks run on every build, against the native method where there is one
- the example: 1+3-2
- numbers with several digits
- spaces anywhere
- a single number, and a leading sign
- a result below zero, and zero
- an empty string is 0
- the weakness: bad input gives a wrong answer instead of an error
A regular expression splits the input into numbers and single characters. Then the loop insists on the shape number (operator number)*: operand() reads optional signs and one number, and anything else throws a SyntaxError that names what was found. The four operators are applied strictly left to right, so 2+3*4 is 20 here. Division by zero throws instead of returning Infinity.
// "Handle all edge cases": split into tokens, then insist on number, operator, number…// All four operators, applied strictly left to right (no precedence), decimals, a leading sign,// and a clear error for anything else.function evaluate(expr) {const tokens = expr.match(/\d+(?:\.\d+)?|\S/g) ?? [];let i = 0;const operand = () => {let sign = 1;while (tokens[i] === '+' || tokens[i] === '-') {if (tokens[i] === '-') sign = -sign;i++;}const token = tokens[i++];if (token === undefined) throw new SyntaxError('expected a number at the end');if (!/^\d/.test(token)) throw new SyntaxError(`expected a number, got "${token}"`);return sign * Number(token);};let total = operand();while (i < tokens.length) {const op = tokens[i++];if (!'+-*/'.includes(op)) throw new SyntaxError(`expected an operator, got "${op}"`);const right = operand();if (op === '+') total += right;else if (op === '-') total -= right;else if (op === '*') total *= right;else if (right === 0) throw new RangeError('division by zero');else total /= right;}return total;}
passes 11 checks run on every build, against the native method where there is one
- the example: 1+3-2
- numbers with several digits
- spaces anywhere
- a single number, and a leading sign
- a result below zero, and zero
- all four operators, strictly left to right (no precedence)
- decimals
- a sign after an operator
- malformed input throws SyntaxError
- the error says what was wrong
- division by zero throws RangeError
The usual follow-up is "now respect precedence". A recursive descent parser has one function per precedence level: expression handles + and - between terms, term handles * and / between factors, and factor is a number, a signed factor, or a bracketed expression. Because term finishes all its multiplications before returning to expression, 2+3*4 is 14. Each loop runs left to right, so 10-3-2 is 5. Anything left over after the top-level expression is an error.
// The follow-up: precedence and brackets. One function per level of the grammar:// expression = term (("+" | "-") term)*// term = factor (("*" | "/") factor)*// factor = ("+" | "-")* (number | "(" expression ")")// A lower level is finished before control returns to the level above, which is precedence.function evaluate(expr) {const tokens = expr.match(/\d+(?:\.\d+)?|\S/g) ?? [];let i = 0;function expression() {let value = term();while (tokens[i] === '+' || tokens[i] === '-') {const op = tokens[i++];const right = term();value = op === '+' ? value + right : value - right;}return value;}function term() {let value = factor();while (tokens[i] === '*' || tokens[i] === '/') {const op = tokens[i++];const right = factor();if (op === '/' && right === 0) throw new RangeError('division by zero');value = op === '*' ? value * right : value / right;}return value;}function factor() {const token = tokens[i++];if (token === '-') return -factor();if (token === '+') return factor();if (token === '(') {const value = expression();if (tokens[i++] !== ')') throw new SyntaxError('missing ")"');return value;}if (token === undefined) throw new SyntaxError('expected a number at the end');if (!/^\d/.test(token)) throw new SyntaxError(`expected a number, got "${token}"`);return Number(token);}const value = expression();if (i < tokens.length) throw new SyntaxError(`unexpected "${tokens[i]}"`);return value;}
passes 12 checks run on every build, against the native method where there is one
- the example: 1+3-2
- numbers with several digits
- spaces anywhere
- a single number, and a leading sign
- a result below zero, and zero
- multiplication and division bind tighter
- equal precedence runs left to right
- brackets, nested
- signs in front of numbers and brackets
- decimals
- malformed input throws SyntaxError
- division by zero throws RangeError
Why not eval
eval('1+3-2') gives 2, and eval of user input runs whatever the user typed. A small parser accepts only the grammar you chose.
Formula fields and calculators
Spreadsheet cells, price rules and calculator inputs are this problem with more operators. They are parsed with the same grammar-per-precedence-level structure.
Decimal results
Numbers are binary floating point, so 0.1+0.2 is 0.30000000000000004. A calculator rounds for display or works in integer cents.
Reading one digit per number, so
12+3becomes 1, 2 and 3.Forgetting to add the last number after the loop ends.
Using
split('+')andsplit('-'), which breaks on a leading minus and on5--3.Skipping unknown characters silently and returning a wrong number.
Reaching for
evalornew Function.Not saying what an empty string, a trailing operator or division by zero should do.
How would you add precedence without recursion?
Keep a stack: push each number; on * or / pop the top, combine it with the next number and push the result; on - push the negated number. At the end, sum the stack. For brackets too, use two stacks (the shunting-yard algorithm).
What's the complexity?
O(n) time for every version: each character is read once. O(1) extra space for the single pass, O(n) for the token list, and the recursion depth of the parser equals the bracket nesting.
How would you support exponent or functions?
Add a grammar level above factor. Exponent is right-associative, so its function calls itself for the right-hand side instead of looping.
How should very large numbers behave?
Above Number.MAX_SAFE_INTEGER integer results lose precision. Use BigInt for integer-only calculators, or a decimal library for money.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding
- en.wikipedia.org/wiki/Recursive_descent_parser
- en.wikipedia.org/wiki/Shunting_yard_algorithm