Skip to content

Commit

Permalink
Merge pull request #132 from mimol91/toInterfaceSlice
Browse files Browse the repository at this point in the history
feat: Add ToAnySlice
  • Loading branch information
samber authored May 10, 2022
2 parents 4fa9fd2 + fda38bb commit c03bb1d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ Supported helpers for slices:
- Reject
- Count
- CountBy
- ToInterfaceSlice

Supported helpers for maps:

Expand Down Expand Up @@ -635,6 +636,14 @@ slice := lo.ReplaceAll(in, -1, 42)
// []int{0, 1, 0, 1, 2, 3, 0}
```

### ToAnySlice

Returns a slice with all elements mapped to any type
```go
elements := lo.ToAnySlice[int]([]int{1, 5, 1})
// []any{1, 5, 1}
```

### Keys

Creates an array of the map keys.
Expand Down
9 changes: 9 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,3 +406,12 @@ func Replace[T comparable](collection []T, old T, new T, n int) []T {
func ReplaceAll[T comparable](collection []T, old T, new T) []T {
return Replace[T](collection, old, new, -1)
}

// ToAnySlice returns a slice with all elements mapped to any type
func ToAnySlice[T any](collection []T) []any {
result := make([]any, len(collection))
for i, item := range collection {
result[i] = item
}
return result
}
12 changes: 12 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,3 +455,15 @@ func TestReplaceAll(t *testing.T) {
is.Equal([]int{42, 1, 42, 1, 2, 3, 42}, out1)
is.Equal([]int{0, 1, 0, 1, 2, 3, 0}, out2)
}

func TestToAnySlice(t *testing.T) {
is := assert.New(t)

in1 := []int{0, 1, 2, 3}
in2 := []int{}
out1 := ToAnySlice(in1)
out2 := ToAnySlice(in2)

is.Equal([]any{0, 1, 2, 3}, out1)
is.Equal([]any{}, out2)
}

0 comments on commit c03bb1d

Please sign in to comment.