feat(pairs): add Pairs-related methods

This commit is contained in:
Piotr Icikowski 2024-05-28 00:19:20 +02:00
parent da6f44a8ed
commit 057f12e602
Signed by: Piotr Icikowski
GPG Key ID: 3931CA47A91F7666
3 changed files with 121 additions and 9 deletions

View File

@ -1,14 +1,5 @@
package generics package generics
// Pair represents key-value pair
type Pair[K comparable, V any] struct {
Key K
Value V
}
// Pairs represents collection of key-value pairs
type Pairs[K comparable, V any] []Pair[K, V]
// MapPairs returns list of map's key-value pairs // MapPairs returns list of map's key-value pairs
func MapPairs[K comparable, V any](src map[K]V) Pairs[K, V] { func MapPairs[K comparable, V any](src map[K]V) Pairs[K, V] {
dst := make([]Pair[K, V], len(src)) dst := make([]Pair[K, V], len(src))

28
pairs.go Normal file
View File

@ -0,0 +1,28 @@
package generics
// Pair represents key-value pair.
type Pair[K comparable, V any] struct {
Key K
Value V
}
// Pairs represents a collection of key-value pairs.
type Pairs[K comparable, V any] []Pair[K, V]
// Keys returns list of key-value pairs' keys.
func (p Pairs[K, V]) Keys() []K {
dst := make([]K, len(p))
for i, pair := range p {
dst[i] = pair.Key
}
return dst
}
// Values returns list of key-value pairs' values.
func (p Pairs[K, V]) Values() []V {
dst := make([]V, len(p))
for i, pair := range p {
dst[i] = pair.Value
}
return dst
}

93
pairs_test.go Normal file
View File

@ -0,0 +1,93 @@
package generics
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPairsKeys(t *testing.T) {
tests := map[string]struct {
src Pairs[string, int]
dst []string
}{
"nil pairs": {
src: nil,
dst: []string{},
},
"empty pairs": {
src: Pairs[string, int]{},
dst: []string{},
},
"filled pairs": {
src: Pairs[string, int]{
{
Key: "foo",
Value: 1,
},
{
Key: "bar",
Value: 2,
},
{
Key: "baz",
Value: 3,
},
},
dst: []string{
"foo",
"bar",
"baz",
},
},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
dst := tc.src.Keys()
require.ElementsMatch(t, tc.dst, dst)
})
}
}
func TestPairsValues(t *testing.T) {
tests := map[string]struct {
src Pairs[string, int]
dst []int
}{
"nil pairs": {
src: nil,
dst: []int{},
},
"empty pairs": {
src: Pairs[string, int]{},
dst: []int{},
},
"filled pairs": {
src: Pairs[string, int]{
{
Key: "foo",
Value: 1,
},
{
Key: "bar",
Value: 2,
},
{
Key: "baz",
Value: 3,
},
},
dst: []int{1, 2, 3},
},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
dst := tc.src.Values()
require.ElementsMatch(t, tc.dst, dst)
})
}
}