Fork me on GitHub

JS Formula

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!

How to Use

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.

Example

		  		
	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
		  		
	  		

Try it!

Result
Error

Functions Included for Demo

							
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;
}
							
						

Why is JS Formula special?

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.

Compare Your Self!

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.

Result
Error

Build Dynamic Reusable Functions

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.

Example

		  		
	var add4 = _eval.getFunction('4 + {x}');
	var result = add4({x: 10});
	//result will be 14