Good afternoon! Here's our prompt for today.
Let's build a very basic calculator by programming it! You've probably seen one that look similar to this:

But we won't be building a physical calculator (HardwareDaily will need to wait!)-- instead, we'll be writing a simple program that can serve as one. Can you write a function that will evaluate a simple expression string without using your language's eval method?
1const expr = "2 + 2";
2calculator(expr)
3// 4It should also be able to handle positive and negative symbols +,-, parentheses (), and spaces.
1let expr = "3 - 1 + 2";
2calculator(expr)
3// 4
4
5expr = "(2+(4+2)-1)-(5+8)"
6calculator(expr)
7// -6Assume for now that you don't need to handle multiplication or division cases.
Constraints
- Length of the given string <=
100000 - The numbers present in the string will be a single digit number
- Expected time complexity :
O(n) - Expected space complexity :
O(n)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx23
var assert = require('assert');​function calculator(str) { // implement this method return str;}​try { assert.equal(calculator('2 + 2'), 4);​ console.log('PASSED: ' + "assert.equal(calculator('2 + 2'), 4)");} catch (err) { console.log(err);}​try { assert.equal(calculator('(2+2) - 3'), 1);​ console.log('PASSED: ' + "assert.equal(calculator('(2+2) - 3'), 1)");} catch (err) { console.log(err);}​OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's how we would solve this problem...
How do I use this guide?

