Created
March 15, 2010 03:44
-
-
Save bcherry/332477 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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