Support Boolean Logic and GTE, LTE, etc in JavaScript Expression Evaluator The JavaScript Expression Evaluator at http://silentmatt.com/javascript-expression-evaluator/ can support basic expressions, but not greater than, equals, less than or equals, AND, OR, etc. These are helpful for Boolean logic equations. To extend it to support these: 1. Add your functions (next after 'concat') function gthan(a, b) { return a > b ? 1 : 0; } function lthan(a, b) { return a < b ? 1 : 0; } function gthane(a, b) { return a > = b ? 1 : 0; } function lthane(a, b) { return a <= b ? 1 : 0; } function notequal(a, b) { return a != b ? 1 : 0; } function equal(a, b) { return a == b ? 1 : 0; } function andLogic(a, b) { return (a != 0 && b != 0) ? 1 : 0; } function orLogic(a, b) { return (a != 0 || b != 0) ? 1 : 0; } 2. Add your operators in the ops2 list: this.ops2 = { "+": add, "-": sub, "*": mul, "/": div, "%": mod, "^": Math.pow, ",": append, "||": concat, "=": equal, " <": lthan, " <=": lthane, "> ": gthan, "> =": gthane, "!=": notequal, " <> ": notequal, "AND": andLogic, "OR": orLogic }; 3. Update isOperator function to recognize your new operators. else if (this.expression.length > this.pos + 1 && (this.expression.substr(this.pos, 2) == " <=" || this.expression.substr(this.pos, 2) == "> =" || this.expression.substr(this.pos, 2) == " <> " || this.expression.substr(this.pos, 2) == "!=")) { this.tokenprio = -2; this.tokenindex = this.expression.substr(this.pos, 2); this.pos++; } else if (this.expression.length > this.pos + 1 && (this.expression.substr(this.pos, 2).toUpperCase() == "OR")) { this.tokenprio = -4; this.tokenindex = this.expression.substr(this.pos, 2).toUpperCase(); this.pos++; } else if (this.expression.length > this.pos + 2 && (this.expression.substr(this.pos, 3).toUpperCase() == "AND")) { this.tokenprio = -3; this.tokenindex = this.expression.substr(this.pos, 3).toUpperCase(); this.pos += 2; } else if (code === 60) { // < this.tokenprio = -2; this.tokenindex = " <"; } else if (code === 62) { // > this.tokenprio = -2; this.tokenindex = "> "; } else if (code === 61) { // = this.tokenprio = -2; this.tokenindex = "="; } Note the lower priority for these operators (solve sides of equation first, then ANDs, last ORs.) And that's it! var expr = Parser.parse("3 <= 3 OR 4 != 5"); var ret = expr.evaluate({ x: 3 }); alert(ret); - returns '1' for true
Created By: amos 2/24/2015 6:24:56 PM Updated: 2/24/2015 6:26:25 PM
|
|