Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function claculate(str) {
- let numbersStack = [];
- let operatorsStack = [];
- let operators = {
- '+' : {
- order : 1,
- func : (r,l) => {return l+r;}
- },
- '-' : {
- order : 1,
- func : (r,l) => {return l-r;}
- },
- '*' : {
- order : 2,
- func : (r,l) => {return l*r;}
- },
- '/' : {
- order : 2,
- func : (r,l) => {return l/r;}
- },
- '^' : {
- order : 3,
- func : (r,l) => {return Math.pow(r,l);}
- },
- '(' : {
- order: 0
- }
- }
- for (let i=0; i<str.length; ++i) {
- if (str[i] === ' ') continue;
- // read the numbers
- if (!isNaN(str[i])) {
- let tmp = "";
- // more then single digit
- while (!isNaN(str[i])) {
- tmp += str[i++];
- }
- numbersStack.push(parseInt(tmp));
- }
- if (str[i] === '(') {
- operatorsStack.push(str[i]);
- } else if (str[i] === ')') {
- // calculate the expression in the parentheses
- while (operatorsStack[operatorsStack.length - 1] !== '(') {
- numbersStack.push(operators[operatorsStack.pop()].func(numbersStack.pop(),numbersStack.pop()));
- }
- operatorsStack.pop();
- } else if (Object.keys(operators).indexOf(str[i]) !== -1) {
- // keep the order of execution
- while (operatorsStack.length !== 0 && operators[operatorsStack[operatorsStack.length - 1]].order >= operators[str[i]].order) {
- numbersStack.push(operators[operatorsStack.pop()].func(numbersStack.pop(),numbersStack.pop()));
- }
- operatorsStack.push(str[i]);
- }
- }
- // calculate remaining operators
- while(operatorsStack.length !== 0) {
- numbersStack.push(operators[operatorsStack.pop()].func(numbersStack.pop(),numbersStack.pop()));
- }
- // last remaning element is the result
- return numbersStack.pop();
- }
- console.log(claculate("2+4")) // 6
- console.log(claculate("1+2 * 3")) // 7
- console.log(claculate("2 * (3 - 1)^4")) // 32
Add Comment
Please, Sign In to add comment