# EvaluateMathematicalExpression

0

0

13

``````var run = function (str) {
return expression(str);
};

var peek = function (str) {
return str[0] || '';
};

var get = function (str) {
return str.shift();
};

var factor = function (str) {

function makeNumber(str) {
var result = '';
while(/[0-9\.]/.test(peek(str))) {
result += get(str);
}
return Number(result);
}

if(peek(str) === "-") {
// rule - factor
get(str);
return -1 * factor(str);
} else if(!isNaN(peek(str))) {
return makeNumber(str);
} else if(peek(str) === "(") {
get(str);  //consume opening parenthesis
var number = expression(str);
get(str); // consume closing parenthesis
return number;
}
};

var term = function (str) {
var result = factor(str);
while (peek(str) == '*' || peek(str) == '/') {
if (get(str) == '*') {
result *= factor(str);
} else {
result /= factor(str);
}
}
return result;
};

var expression = function (str) {
var result = term(str);
while (peek(str) == '+' || peek(str) == '-') {
if (get(str) == '+') {
result += term(str);
} else {
result -= term(str);
}
}
return result;
};

var calc = function (expression) {
var expressionToParse = expression.replace(/\s+/g, '').split('');
return run(expressionToParse);
}

console.log(calc("3+4+5"))
``````
• Rulesets
• Playground
• Snippets
• Cookbooks
###### Legal

We are SOC-2 Compliance Certified