I am currently using the golang package github.com/Knetic/govaluate
to evaluate formulas from database. Here is an example of a formula I am using in my database
expression, err := govaluate.NewEvaluableExpression("totalCost / .85"); // for markup
parameters := make(map[string]interface{})
parameters["cost"] = 9.99;
parameters["qty"] = 2;
parameters["markup"] = nil // totalCost / .85 (this formula above)
parameters["handlingCharge"] = nil // if(cost > 100, 25, cost * 0.1).
parameters["totalCost"] = nil // (cost * qty) + handlingCharge.
result, err := expression.Evaluate(parameters);
handlingCharge
and totalCost
are also formulas. There is no limit (except circular references) on formulas containing other formula fields. Think of it like excel formula referencing another formula field.
Instead of coding x
amount of for loops to check if each required variable field has another variable field, how can I effectually work each required formula?
// expressions map
var expressionsMap = make(map[string]*govaluate.EvaluableExpression)
var requiredVariables = make(map[string][]string)
// for each table field
for publicID, formula := range fieldsMap {
// get expression into map
if formula != "" {
expression, err := govaluate.NewEvaluableExpressionWithFunctions(formula, functions)
if err != nil {
log.Println(err)
return nil, errInternalServerError
}
// save expression to expressions map
expressionsMap[publicID] = expression
// save required variables to a map of required variables
requiredVariables[publicID] = unique(expression.Vars())
}
}
For this simple example requiredVariables
would be
requiredVariables['handlingCharge'] = ['cost']
requiredVariables['markup'] = ['totalCost']
requiredVariables['totalCost'] = ['cost', 'qty', 'handlingCharge']
In total markup
requires totalCost
and totalCost
needs handlingCharge
. How can I programmatically calculate these formulas? Thank you for the help.