From 38d4d2f9d45259f58a75cd966a90ff8a473b46ba Mon Sep 17 00:00:00 2001 From: Joshua Spence Date: Wed, 26 Apr 2017 07:41:33 +1000 Subject: [PATCH] Add a logarithm function Fixes #9498. Adds a `log` function for calculating logarithms. --- config/interpolate_funcs.go | 12 ++++++++ config/interpolate_funcs_test.go | 28 +++++++++++++++++++ .../docs/configuration/interpolation.html.md | 2 ++ 3 files changed, 42 insertions(+) diff --git a/config/interpolate_funcs.go b/config/interpolate_funcs.go index 4962d4f37c..f1f97b04e4 100644 --- a/config/interpolate_funcs.go +++ b/config/interpolate_funcs.go @@ -81,6 +81,7 @@ func Funcs() map[string]ast.Function { "jsonencode": interpolationFuncJSONEncode(), "length": interpolationFuncLength(), "list": interpolationFuncList(), + "log": interpolationFuncLog(), "lower": interpolationFuncLower(), "map": interpolationFuncMap(), "max": interpolationFuncMax(), @@ -489,6 +490,17 @@ func interpolationFuncCeil() ast.Function { } } +// interpolationFuncLog returns the logarithnm. +func interpolationFuncLog() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeFloat, ast.TypeFloat}, + ReturnType: ast.TypeFloat, + Callback: func(args []interface{}) (interface{}, error) { + return math.Log(args[0].(float64)) / math.Log(args[1].(float64)), nil + }, + } +} + // interpolationFuncChomp removes trailing newlines from the given string func interpolationFuncChomp() ast.Function { newlines := regexp.MustCompile(`(?:\r\n?|\n)*\z`) diff --git a/config/interpolate_funcs_test.go b/config/interpolate_funcs_test.go index b0c7bafffb..6ed65a6f4c 100644 --- a/config/interpolate_funcs_test.go +++ b/config/interpolate_funcs_test.go @@ -370,6 +370,34 @@ func TestInterpolateFuncCeil(t *testing.T) { }) } +func TestInterpolateFuncLog(t *testing.T) { + testFunction(t, testFunctionConfig{ + Cases: []testFunctionCase{ + { + `${log(1, 10)}`, + "0", + false, + }, + { + `${log(10, 10)}`, + "1", + false, + }, + + { + `${log(0, 10)}`, + "-Inf", + false, + }, + { + `${log(10, 0)}`, + "-0", + false, + }, + }, + }) +} + func TestInterpolateFuncChomp(t *testing.T) { testFunction(t, testFunctionConfig{ Cases: []testFunctionCase{ diff --git a/website/source/docs/configuration/interpolation.html.md b/website/source/docs/configuration/interpolation.html.md index 3b855cdee6..b8e38e9f0b 100644 --- a/website/source/docs/configuration/interpolation.html.md +++ b/website/source/docs/configuration/interpolation.html.md @@ -278,6 +278,8 @@ The supported built-in functions are: * `${list("a", "b", "c")}` returns a list of `"a", "b", "c"`. * `${list()}` returns an empty list. + * `log(x, base)` - Returns the logarithm of `x`. + * `lookup(map, key, [default])` - Performs a dynamic lookup into a map variable. The `map` parameter should be another variable, such as `var.amis`. If `key` does not exist in `map`, the interpolation will