Skip to content

Instantly share code, notes, and snippets.

@bcherry
Created March 15, 2010 03:44
Show Gist options
  • Save bcherry/332477 to your computer and use it in GitHub Desktop.
Save bcherry/332477 to your computer and use it in GitHub Desktop.
// Simple arithemetic parser.
// Follows order of operations, only supports positive integers
// Only operators are +, -, *, and /. Does not support grouping with ()
var calc = (function () {
var calc,
sum,
negasum,
product,
dividend;
sum = function(args) {
var r = calc(args[0]),
i,
l;
for (i = 1, l = args.length; i < l; i += 1) {
r += calc(args[i]);
}
return r;
};
negasum = function(args) {
var r = calc(args[0]),
i,
l;
for (i = 1, l = args.length; i < l; i += 1) {
r -= calc(args[i]);
}
return r;
};
product = function(args) {
var r = calc(args[0]),
i,
l;
for (i = 1, l = args.length; i < l; i += 1) {
r *= calc(args[i]);
}
return r;
};
dividend = function(args) {
var r = calc(args[0]),
i,
l;
for (i = 1, l = args.length; i < l; i += 1) {
r /= calc(args[i]);
}
return r;
};
calc = function(input) {
if (input.indexOf("+") >= 0) {
return sum(input.split("+"));
} else if (input.indexOf("-") >= 0) {
return negasum(input.split("-"));
} else if (input.indexOf("*") >= 0) {
return product(input.split("*"));
} else if (input.indexOf("/") >= 0) {
return dividend(input.split("/"));
} else {
return parseInt(input, 10);
}
};
return calc;
}());
// Robust test suite, benchmarked against native eval()
var string = "1+1*2+5-10/2";
console.log("calc(%s) -> %o", string, calc(string));
console.log("eval(%s) -> %o", string, eval(string));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment