Skip to content

Commit 48b44a2

Browse files
committed
fix: return a new slice on funk.Uniq and avoid mutate input (fixes #87)
1 parent 9d915e4 commit 48b44a2

File tree

3 files changed

+12
-9
lines changed

3 files changed

+12
-9
lines changed

transform.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,8 @@ func Uniq(in interface{}) interface{} {
313313
if kind == reflect.Array || kind == reflect.Slice {
314314
length := value.Len()
315315

316+
result := makeSlice(value, 0)
317+
316318
seen := make(map[interface{}]bool, length)
317319
j := 0
318320

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

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

335-
return value.Slice(0, j).Interface()
334+
return result.Interface()
336335
}
337336

338337
panic(fmt.Sprintf("Type %s is not supported by Uniq", valueType.String()))

transform_test.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,13 +134,15 @@ func TestReverse(t *testing.T) {
134134
}
135135

136136
func TestUniq(t *testing.T) {
137-
results := Uniq([]int{0, 1, 1, 2, 3, 0, 0, 12})
138-
139137
is := assert.New(t)
140138

139+
results := Uniq([]int{0, 1, 1, 2, 3, 0, 0, 12})
141140
is.Len(results, 5)
142-
143141
is.Equal(results, []int{0, 1, 2, 3, 12})
142+
143+
results = Uniq([]string{"foo", "bar", "foo", "bar", "bar"})
144+
is.Len(results, 2)
145+
is.Equal(results, []string{"foo", "bar"})
144146
}
145147

146148
func TestConvertSlice(t *testing.T) {

utils.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package funk
22

3-
import "reflect"
3+
import (
4+
"reflect"
5+
)
46

57
func equal(expected, actual interface{}) bool {
68
if expected == nil || actual == nil {

0 commit comments

Comments
 (0)