function parseExpression(expression) {
var tokens = expression.split(' ');
var stack = [];
var output = [];
var precedence = {
'+': 1,
'-': 1,
'*': 2,
'/': 2
};
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (!isNaN(token)) {
output.push(token);
} else if (token in precedence) {
while (stack.length > 0 && stack[stack.length - 1] in precedence && precedence[stack[stack.length - 1]] >= precedence[token]) {
output.push(stack.pop());
}
stack.push(token);
} else if (token == '(') {
stack.push(token);
} else if (token == ')') {
while (stack.length > 0 && stack[stack.length - 1] != '(') {
output.push(stack.pop());
}
stack.pop();
}
}
while (stack.length > 0) {
output.push(stack.pop());
}
var stack = [];
for (var i = 0; i < output.length; i++) {
var token = output[i];
if (!isNaN(token)) {
stack.push(parseFloat(token));
} else {
var b = stack.pop();
var a = stack.pop();
if (token == '+') {
stack.push(a + b);
} else if (token == '-') {
stack.push(a - b);
} else if (token == '*') {
stack.push(a * b);
} else if (token == '/') {
stack.push(a / b);
}
}
}
return stack.pop();
}
var expression = '13 + 4 * ( 12 - 1 )';
var value = parseExpression(expression);
console.log(value);
console