Lesson 8 of 8 · 25 min

Challenge: Build a mini calculator

Arjun's little sister has maths homework, and Arjun has a plan: a calculator where you type the whole sum, like 2 + 3 * 4, and get the answer. The catch is that a calculator that just goes left to right gets it wrong:

2 + 3 * 4   left to right: 5 * 4 = 20   wrong
            maths rules:   2 + 12 = 14   right

Multiplication and division happen before addition and subtraction, and brackets come before everything.

Your task

Write calculate(expression). It takes a sum as text and returns its value as a number.

calculate("2 + 3 * 4")                 // 14
calculate("10 - 4 - 3")                // 3
calculate("7 / 2")                     // 3.5
calculate("(2 + 3) * 4")               // 20
calculate("((1 + 2) * (3 + 4)) - 1")   // 20
calculate("2*3+4")                     // 10

Rules

  • Numbers are whole numbers, 0 or more, and can have several digits (120). There are no negative numbers like -5.
  • The operators are +, -, * and /. Division is normal division, so 7 / 2 is 3.5.
  • * and / come before + and -. Operators at the same level work left to right: 10 - 4 - 3 is 3.
  • Brackets ( ) can be nested as deep as you like.
  • Spaces may appear anywhere, or not at all.
  • Every sum you get is valid, and nothing is divided by zero.
  • No eval or new Function: the point is to do the maths yourself!

Tips

  • Step 1, tokens. Turn "12+(3*4)" into a list: [12, "+", "(", 3, "*", 4, ")"]. Collect digits that are next to each other into one number, and skip spaces.
  • Step 2, three small functions that share a position in the token list:
    • expression() reads a term(), then while the next token is + or -, reads another term() and adds or subtracts it.
    • term() does the same with factor() and * or /.
    • factor() reads a number, or, if the token is (, reads a whole expression() and then skips the ).
  • Because expression calls term and term calls factor, multiplication is always finished before addition. And because factor can call expression, brackets work at any depth.
  • Functions written inside calculate can all see and change the same position variable (a closure).
main.js
function calculate(expression) {
  // TODO: split into tokens, then work out the value
  // with * and / before + and -, and brackets first.
  return 0;
}

console.log(calculate("2 + 3 * 4"));    // should print 14
console.log(calculate("(2 + 3) * 4"));  // should print 20

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…