JS Formula is Javascript utility that enables formula evaluation without the use of eval().
Users can perform evaluation on JSON objects using the built in mathmatical opperators
+, - , / and * as well as define custom functions that the evaluator can use.
Try it out!
JS Formula can evaluate formulas and return the result. If you want to use variables in your formulas make sure to wrap the variable in curly braces. To access nested attributes, place a dot in between the variable names. When you evaluate your formula, place the object with the variables as the second argument.
To use your own functions in JS Formula create a key to function JSON object, and set it as the function set by calling the setFunctions method. After following these steps you can access your functions in the formula using the key you used in the JSON object.
var functions = {
'sin' : function(x) {
return Math.sin(x)
},
'pow' : function(x,y) {
return Math.pow(x,y)
}
}
_eval.setFunctions(functions)
var formula = '{x} + 5';
var obj = {x:20};
var results = _eval(formula,obj);
//results will be 25
function(x) {
return Math.sin(x)
}
function(x,y) {
return Math.pow(x,y)
}
function(values) {
if (!values) {
return null;
} else {
var max = Number.MIN_VALUE
values.forEach(function(x) {
if (x > max) {
max = x;
}
})
return max;
}
}
function(a) {
return a.length
}
function(a) {
var total = 0;
a.forEach(function(x){
total += x
});
return total;
}
What sets JS Formula appart from other JavaScript formula evaluators is how it evaluates the formula. JS Formula does not just simply evaluate formula's, but instead builds a Formula object that can be traversed and evaluated. By taking this approach, the Formula object can be cached, which provides significant performance increase the next time the same formula string is asked to be evaluated, even with different objects.
The function you enter here will be evaluate 10,000 times by both the uncached version and the cached version. It will then output how long it took to evaluate the 10,000 formulas for each version. The functions in the previous demo are still available.
JS Formula is able to build functions based on formulas. The function can then be called with a an object parameter and will return the output of the formula used to define the function.
var add4 = _eval.getFunction('4 + {x}');
var result = add4({x: 10});
//result will be 14