Skip to content

Commit

Permalink
Add uniq function.
Browse files Browse the repository at this point in the history
Closes #30
  • Loading branch information
technosophos committed Mar 13, 2017
1 parent 586619b commit a1c06b6
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
2 changes: 2 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ These are used to manipulate lists: '{{ list 1 2 3 | reverse | first }}'
- initial: Get all but the last item in a list: 'list 1 2 3 | initial' returns '[1 2]'
- append: Add an item to the end of a list: 'append $list 4' adds '4' to the end of '$list'
- prepend: Add an item to the beginning of a list: 'prepend $list 4' puts 4 at the beginning of the list.
- reverse: Reverse the items in a list.
- uniq: Remove duplicates from a list.
Dict Functions:
Expand Down
1 change: 1 addition & 0 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ var genericMap = map[string]interface{}{
"last": last,
"initial": initial,
"reverse": reverse,
"uniq": uniq,

// Crypto:
"genPrivateKey": generatePrivateKey,
Expand Down
20 changes: 20 additions & 0 deletions list.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,23 @@ func compact(list []interface{}) []interface{} {
}
return res
}

func uniq(list []interface{}) []interface{} {
dest := []interface{}{}

skip := func(haystack []interface{}, needle interface{}) bool {
for _, h := range haystack {
if reflect.DeepEqual(needle, h) {
return true
}
}
return false
}

for _, item := range list {
if !skip(dest, item) {
dest = append(dest, item)
}
}
return dest
}
13 changes: 13 additions & 0 deletions list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,16 @@ func TestReverse(t *testing.T) {
assert.NoError(t, runt(tpl, expect))
}
}

func TestUniq(t *testing.T) {
tests := map[string]string{
`{{ list 1 2 3 4 | uniq }}`: `[1 2 3 4]`,
`{{ list "a" "b" "c" "d" | uniq }}`: `[a b c d]`,
`{{ list 1 1 1 1 2 2 2 2 | uniq }}`: `[1 2]`,
`{{ list "foo" 1 1 1 1 "foo" "foo" | uniq }}`: `[foo 1]`,
`{{ list | uniq }}`: `[]`,
}
for tpl, expect := range tests {
assert.NoError(t, runt(tpl, expect))
}
}

0 comments on commit a1c06b6

Please sign in to comment.