-
-
Save pajcho/c5bbfa805f8993b66900 to your computer and use it in GitHub Desktop.
Conditionally restrict available operators
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
'use strict'; | |
export class Expression { | |
constructor(allowedOperators = []) { | |
this.expressionString = ''; | |
this.allowedOperators = allowedOperators; | |
} | |
parse(expressionString) { | |
// Make sure we have sane arguments. | |
if (typeof expressionString != 'string') return; | |
this.expressionString = expressionString; | |
// Make sure all variables (and functions) are lower-case. | |
this.expressionString = this.expressionString.toLowerCase(); | |
// Parse! Since Parser may throw errors, we need a try statement. | |
try { | |
// Special handling if we should restrict allowed operators. | |
if (!this.allowedOperators.length) { | |
return window.Parser.parse(this.expressionString); | |
} | |
return this.filterAllowedOperators(); | |
} | |
catch(e) { | |
return; | |
} | |
} | |
filterAllowedOperators() { | |
var expr = window.Parser.parse(this.expressionString); | |
// Manipulate ops1, ops2 and functions of the expression object. | |
for (var op in {ops1 : 'ops1', ops2 : 'ops2', functions : 'functions'}) { | |
for (var i in expr[op]) { | |
// Never remove the negative sign as operator. | |
if (op == 'ops1' && i == '-') { | |
continue; | |
} | |
if (this.allowedOperators.indexOf(i) < 0) { | |
// We cannot delete the function, since it not a property. Instead we | |
// set it to something awkward, which will fail evaluation if the | |
// function is used. | |
expr[op][i] = undefined; | |
} | |
} | |
} | |
return expr; | |
} | |
} |
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
import {Expression} from 'expression.helper'; | |
var expressionString = '(A + B) / 2'; | |
var parser = new Expression(['(', ')', '+', '-', '/', '*']); | |
var expression = parser.parse(expressionString); | |
// And now in order to evaluate you just have to pass array of variable values | |
var variables = {'A': 10, 'B': 5}; | |
var result = expression.evaluate(variables); // Will give you 1 as a result | |
// In case anything fails, evaluate() will return 'undefined' as a result. | |
// This include invalid expression (usage of wrong operator) or missing variable, etc. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment