Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

39 řádky
1.0KB

  1. package template
  2. import (
  3. "errors"
  4. "fmt"
  5. "gopkg.in/Knetic/govaluate.v3"
  6. )
  7. // ErrNonFloatValue is returned when the result of the expression is not a float64.
  8. var ErrNonFloatValue = errors.New("failed to cast expression result for float64")
  9. // Value describes a measurement or dimension in the templates.
  10. type Value string
  11. // Evaluate a Value as [govaluate.EvaluateExpression] in combination with the provided parameters.
  12. func (v *Value) Evaluate(parameters govaluate.MapParameters, funcs map[string]govaluate.ExpressionFunction) (float64, error) {
  13. if v == nil {
  14. return 0, nil
  15. }
  16. expression, err := govaluate.NewEvaluableExpressionWithFunctions(string(*v), funcs)
  17. if err != nil {
  18. return 0, fmt.Errorf("create new evaluable expression for %q: %w", *v, err)
  19. }
  20. result, err := expression.Evaluate(parameters)
  21. if err != nil {
  22. return 0, fmt.Errorf("evaluable expression for %q: %w", *v, err)
  23. }
  24. f, ok := result.(float64)
  25. if !ok {
  26. return 0, fmt.Errorf("cast %v to float: %w", result, ErrNonFloatValue)
  27. }
  28. return f, nil
  29. }