Add pow function

This commit is contained in:
Pradeep Bhadani 2017-05-17 21:46:33 +00:00
parent 8df29ccde6
commit 47b1aaea3a
3 changed files with 66 additions and 0 deletions

View File

@ -89,6 +89,7 @@ func Funcs() map[string]ast.Function {
"merge": interpolationFuncMerge(),
"min": interpolationFuncMin(),
"pathexpand": interpolationFuncPathExpand(),
"pow": interpolationFuncPow(),
"uuid": interpolationFuncUUID(),
"replace": interpolationFuncReplace(),
"sha1": interpolationFuncSha1(),
@ -394,6 +395,17 @@ func interpolationFuncConcat() ast.Function {
}
}
// interpolationFuncPow returns base x exponential of y.
func interpolationFuncPow() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeFloat, ast.TypeFloat},
ReturnType: ast.TypeFloat,
Callback: func(args []interface{}) (interface{}, error) {
return math.Pow(args[0].(float64), args[1].(float64)), nil
},
}
}
// interpolationFuncFile implements the "file" function that allows
// loading contents from a file.
func interpolationFuncFile() ast.Function {

View File

@ -310,6 +310,54 @@ func TestInterpolateFuncMin(t *testing.T) {
})
}
func TestInterpolateFuncPow(t *testing.T) {
testFunction(t, testFunctionConfig{
Cases: []testFunctionCase{
{
`${pow(1, 0)}`,
"1",
false,
},
{
`${pow(1, 1)}`,
"1",
false,
},
{
`${pow(2, 0)}`,
"1",
false,
},
{
`${pow(2, 1)}`,
"2",
false,
},
{
`${pow(3, 2)}`,
"9",
false,
},
{
`${pow(-3, 2)}`,
"9",
false,
},
{
`${pow(2, -2)}`,
"0.25",
false,
},
{
`${pow(0, 2)}`,
"0",
false,
},
},
})
}
func TestInterpolateFuncFloor(t *testing.T) {
testFunction(t, testFunctionConfig{
Cases: []testFunctionCase{

View File

@ -312,6 +312,12 @@ The supported built-in functions are:
* `pathexpand(string)` - Returns a filepath string with `~` expanded to the home directory. Note:
This will create a plan diff between two different hosts, unless the filepaths are the same.
* `pow(x, y)` - Returns the base `x` of exponential `y`.
Example:
* `${pow(3,2)}` = 9
* `${pow(4,0)}` = 1
* `replace(string, search, replace)` - Does a search and replace on the
given string. All instances of `search` are replaced with the value
of `replace`. If `search` is wrapped in forward slashes, it is treated