diff --git a/transform.go b/transform.go index a0ad3b7..f2429ce 100644 --- a/transform.go +++ b/transform.go @@ -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 @@ -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())) diff --git a/transform_test.go b/transform_test.go index 20114a8..2c4a0dc 100644 --- a/transform_test.go +++ b/transform_test.go @@ -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) { diff --git a/utils.go b/utils.go index 657484b..46ac67e 100644 --- a/utils.go +++ b/utils.go @@ -1,6 +1,8 @@ package funk -import "reflect" +import ( + "reflect" +) func equal(expected, actual interface{}) bool { if expected == nil || actual == nil {