0
  const calculate = (s) => {
    let code;
    let index;
    let startIndex;
    let stackSign = [];
    let result = [0];
    let numberSign = 1;

    for (var i = 0; i < s.length; i++) {
      if (s[i] === ' ') {
        continue;
      } else if (s[i] === '(') {
        stackSign.push(numberSign);
        result.push(0);
        numberSign = 1;
      } else if (s[i] === ')') {
        result[result.length - 2] += result.pop() * stackSign.pop();
      } else if (s[i] === '+') {
        numberSign = 1;
      } else if (s[i] === '-') {
        numberSign = -1;
      } else if (s[i] === '/') {
        numberSign = result / 1;
      } else if (s[i] === '*') {
        numberSign = result * 1;
      } else {
        startIndex = i;
        while (
          (index = i + 1) < s.length &&
          (code = s[index].charCodeAt()) > 47 &&
          code < 58
        ) {
          i++;
        }
        result[result.length - 1] +=
          +s.substring(startIndex, i + 1) * numberSign;
      }
    }

    return result.pop();
  };

Hello guys i made this algorithm to create a calculator without javascript "eval" but im struggling to add the * and / operators, can you guys help me with that? thanks

How i'm using it:

  calculate('50 + 50');
  • 2
    Your current code has many issues besides not correctly implementing multiplication or division. I'd recommend not trying to solve everything at once, but start with something small that works and adding operations once you have some other (more basic ones) working. Currently, your question raises way to many issues to answer here, other than just rewriting your solution. – Grismar May 29 '20 at 00:41
  • You have any suggestion or there is a algorithm like that i can take as example? – Isac Santos May 29 '20 at 00:52
  • See https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval/47761792#47761792 for a great solution by @trincot. – Trentium May 29 '20 at 02:12

0 Answers0