var expr = '5+4-3*2/3';
var parsers = [{
symbol: '-',
fn: function (a, b) {
return a - b;
}
}, {
symbol: '+',
fn: function (a, b) {
return a + b;
}
}, {
symbol: '/',
fn: function (a, b) {
return a / b;
}
}, {
symbol: '*',
fn: function (a, b) {
return a * b;
}
}];
var parse = function (expr, level) {
if (!expr) {
throw new Error('Wrong expression: "' + expr + '".');
}
if (level === void(0)) {
level = 0;
}
if (level === parsers.length) {
// Return value
return parseFloat(expr.trim());
}
// Get parser at current level
var parser = parsers[level];
// Get symbol position
var index = expr.indexOf(parser.symbol);
if (index < 0) {
// Not found -> parse at next level
return parse(expr, level + 1);
} else {
// Split and evaluate
var part1 = expr.slice(0, index);
var part2 = expr.slice(index + 1, expr.length);
var arg1 = parse(part1, level);
var arg2 = parse(part2, level);
return parser.fn(arg1, arg2);
}
};
debugger;
var result = parse(expr);
alert(result);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.