Skip to content
This repository has been archived by the owner on Aug 21, 2024. It is now read-only.

Commit

Permalink
Add unique function
Browse files Browse the repository at this point in the history
  • Loading branch information
cam-stitt committed Dec 21, 2017
1 parent 49a9c63 commit 469dd8f
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
3 changes: 3 additions & 0 deletions interpolation/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ var CoreFunctions = map[string]ast.Function{
"split": interpolationFuncSplit(),
"length": interpolationFuncLength(),
"jsonencode": interpolationFuncJSONEncode(),
"pick": interpolationFuncPick(),
"omit": interpolationFuncOmit(),
"unique": interpolationFuncUnique(),
}

// interpolationFuncEnv will extract a variable out of the env
Expand Down
28 changes: 28 additions & 0 deletions interpolation/lists.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package interpolation
import (
"fmt"

"reflect"

"github.com/hashicorp/hil/ast"
)

Expand Down Expand Up @@ -62,3 +64,29 @@ func interpolationFuncConcat() ast.Function {
},
}
}

// interpolationFuncUnique will extract the unique values and return a list
func interpolationFuncUnique() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeList},
ReturnType: ast.TypeList,
Callback: func(inputs []interface{}) (interface{}, error) {
list := inputs[0].([]ast.Variable)
result := make([]ast.Variable, 0, len(list))

for _, val := range list {
exists := false
for _, r := range result {
if reflect.DeepEqual(val, r) {
exists = true
}
}
if !exists {
result = append(result, val)
}
}

return result, nil
},
}
}
31 changes: 30 additions & 1 deletion interpolation/lists_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func TestInterpolationFuncList(t *testing.T) {
}
}

func TestInterpoloationFuncConcat(t *testing.T) {
func TestInterpolationFuncConcat(t *testing.T) {
testCases := []functionTestCase{
{
description: "Two lists combine",
Expand Down Expand Up @@ -93,3 +93,32 @@ func TestInterpoloationFuncConcat(t *testing.T) {
})
}
}

func TestInterpolationFuncUnique(t *testing.T) {
testCases := []functionTestCase{
{
description: "Extracts unique values",
text: `${unique(list("1", "2", "1"))}`,
expectation: []interface{}{"1", "2"},
},
{
description: "Extract unique complex values",
text: `${unique(list(list("1", "2", "3"), list("1", "2"), list("1", "2", "3")))}`,
expectation: []interface{}{
[]interface{}{"1", "2", "3"},
[]interface{}{"1", "2"},
},
},
}

uniqueTestFunc := testInterpolationFunc(keyFuncs{
"unique": interpolationFuncUnique,
"list": interpolationFuncList,
})

for _, tc := range testCases {
t.Run(tc.description, func(t *testing.T) {
uniqueTestFunc(t, tc)
})
}
}

0 comments on commit 469dd8f

Please # to comment.