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, so7 / 2is3.5. *and/come before+and-. Operators at the same level work left to right:10 - 4 - 3is 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
evalornew 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 aterm(), then while the next token is+or-, reads anotherterm()and adds or subtracts it.term()does the same withfactor()and*or/.factor()reads a number, or, if the token is(, reads a wholeexpression()and then skips the).
- Because
expressioncallstermandtermcallsfactor, multiplication is always finished before addition. And becausefactorcan callexpression, brackets work at any depth. - Functions written inside
calculatecan all see and change the samepositionvariable (a closure).