Skip to content

Commit

Permalink
fix: return a new slice on funk.Uniq and avoid mutate input (fixes #87)
Browse files Browse the repository at this point in the history
  • Loading branch information
thoas committed Jun 23, 2020
1 parent 9d915e4 commit 48b44a2
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 9 deletions.
9 changes: 4 additions & 5 deletions transform.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,8 @@ func Uniq(in interface{}) interface{} {
if kind == reflect.Array || kind == reflect.Slice {
length := value.Len()

result := makeSlice(value, 0)

seen := make(map[interface{}]bool, length)
j := 0

Expand All @@ -325,14 +327,11 @@ func Uniq(in interface{}) interface{} {
}

seen[v] = true
// Edits the original to add only unique elements.
// If there are j unique elements in the input, it will be modified to contain the unique elements from
// from index 0 through j
value.Index(j).Set(val)
result = reflect.Append(result, val)
j++
}

return value.Slice(0, j).Interface()
return result.Interface()
}

panic(fmt.Sprintf("Type %s is not supported by Uniq", valueType.String()))
Expand Down
8 changes: 5 additions & 3 deletions transform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,13 +134,15 @@ func TestReverse(t *testing.T) {
}

func TestUniq(t *testing.T) {
results := Uniq([]int{0, 1, 1, 2, 3, 0, 0, 12})

is := assert.New(t)

results := Uniq([]int{0, 1, 1, 2, 3, 0, 0, 12})
is.Len(results, 5)

is.Equal(results, []int{0, 1, 2, 3, 12})

results = Uniq([]string{"foo", "bar", "foo", "bar", "bar"})
is.Len(results, 2)
is.Equal(results, []string{"foo", "bar"})
}

func TestConvertSlice(t *testing.T) {
Expand Down
4 changes: 3 additions & 1 deletion utils.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package funk

import "reflect"
import (
"reflect"
)

func equal(expected, actual interface{}) bool {
if expected == nil || actual == nil {
Expand Down

0 comments on commit 48b44a2

Please sign in to comment.