Created
October 19, 2018 12:44
-
-
Save e-mihaylin/5c1e0effa3455882a9d5767682bd26be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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