Skip to content

Commit

Permalink
add SliceUniqStable
Browse files Browse the repository at this point in the history
  • Loading branch information
kazhuravlev committed Dec 1, 2023
1 parent 3bcdea5 commit 622c349
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
18 changes: 18 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,24 @@ func SliceUniq[T comparable](in []T) []T {
return res
}

// SliceUniqStable returns unique values from `in`. Keep original ordering.
func SliceUniqStable[T comparable](in []T) []T {
index := make(map[T]struct{}, len(in))

res := make([]T, 0, len(in))
for i := range in {
if MapContainsKey(index, in[i]) {
continue
}

index[in[i]] = struct{}{}

res = append(res, in[i])
}

return res
}

// SliceMap returns the slice where each element of `in` was handled by `fn`.
func SliceMap[T any, V any](in []T, fn func(T) V) []V {
if len(in) == 0 {
Expand Down
56 changes: 56 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,62 @@ func TestUniq(t *testing.T) {
}
}

func TestSliceUniqStable(t *testing.T) {
t.Parallel()

table := []struct {
name string
in []int
exp []int
}{
{
name: "empty_nil",
in: nil,
exp: []int{},
},
{
name: "empty_len0",
in: []int{},
exp: []int{},
},
{
name: "uniq_1",
in: []int{1},
exp: []int{1},
},
{
name: "uniq_3",
in: []int{1, 2, 3},
exp: []int{1, 2, 3},
},
{
name: "non_uniq_3",
in: []int{1, 2, 1, 3, 1},
exp: []int{1, 2, 3},
},
{
name: "non_uniq_6_unordered",
in: []int{1, 2, 1, 3, 1, 4},
exp: []int{1, 2, 3, 4},
},
{
name: "non_uniq_100",
in: make([]int, 100),
exp: []int{0},
},
}

for _, row := range table {
row := row
t.Run(row.name, func(t *testing.T) {
t.Parallel()

res := just.SliceUniqStable(row.in)
require.EqualValues(t, row.exp, res)
})
}
}

func TestSliceReverse(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 622c349

Please sign in to comment.