Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2210,6 +2210,37 @@ Zip iteratively merges together the values of the slice parameters with the valu
</p>
</details>

## func [ToMap](<https://github.com/esimov/gogu/blob/master/slice.go#L552>)

```go
func ToMap[T, K comparable](slice []T, fn func(x T) K) map[K]T
```

Converts slice to map, where keys are generated with `fn` function.

<details><summary>Example</summary>
<p>

```go
{
slice := []int{1, 2, 3}
result := ToMap(slice, func(x int) int { return x })
}
```

#### Output

```
{1: 1, 2: 2, 3: 3}
```

</p>
</details>





## type [Bound](<https://github.com/esimov/gogu/blob/master/find.go#L180-L182>)

```go
Expand Down
10 changes: 10 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -547,3 +547,13 @@ func ToSlice[T any](args ...T) []T {

return slice
}

// ToMap convert slice to map
func ToMap[T, K comparable](slice []T, fn func(x T) K) map[K]T {
result := make(map[K]T, len(slice))
for _, v := range slice {
k := fn(v)
result[k] = v
}
return result
}
31 changes: 31 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -688,3 +688,34 @@ func Example_unzip() {
// Output:
// [[one two] [1 2]]
}

func TestSlice_ToMap(t *testing.T) {
type some_struct struct {
Id uint
Title string
}

s1 := some_struct{Id: 1, Title: "foo"}
s2 := some_struct{Id: 10, Title: "bar"}
s3 := some_struct{Id: 100, Title: "baz"}

input := []some_struct{
s1,
s2,
s3,
}

result := ToMap(input, func(x some_struct) uint { return x.Id })

assert := assert.New(t)
assert.True(len(result) == 3)
assert.Equal(map[uint]some_struct{s1.Id: s1, s2.Id: s2, s3.Id: s3}, result)
}

func Example_toMap() {
slice := []int{1, 2, 3}
result := ToMap(slice, func(x int) int { return x })

fmt.Println(result)
// {1: 1, 2: 2, 3: 3}
}