Skip to content

Instantly share code, notes, and snippets.

@e-mihaylin
Created October 19, 2018 12:44
Show Gist options
  • Save e-mihaylin/5c1e0effa3455882a9d5767682bd26be to your computer and use it in GitHub Desktop.
Save e-mihaylin/5c1e0effa3455882a9d5767682bd26be to your computer and use it in GitHub Desktop.
class Calculator {
evaluate (s) {
s = s.replace(/\s/g, '');
const l = s.length;
const stack = [];
let i = 0;
let o = '+';
while (i < l) {
const x = s[i];
if (/\d/.test(x)) {
const start = i;
while (i < l && /\d|\./.test(s[i])) i++;
i--;
const temp = +s.slice(start, i + 1);
if (o === '+') stack.push(temp);
if (o === '-') stack.push(-temp);
if (o === '*') stack.push(stack.pop() * temp);
if (o === '/') stack.push(stack.pop() / temp);
} else o = x;
i++;
}
return stack.reduce((r, e) => r + e, 0);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment