fn: Added map functions

Signed-off-by: Ononiwu Maureen <59079323+Chinwendu20@users.noreply.github.com>
This commit is contained in:
Ononiwu Maureen
2024-05-05 21:05:29 +01:00
parent 399ea864da
commit f88f120e91
2 changed files with 179 additions and 0 deletions

44
fn/map.go Normal file
View File

@@ -0,0 +1,44 @@
package fn
import (
"fmt"
"golang.org/x/exp/maps"
)
// KeySet converts a map into a Set containing the keys of the map.
func KeySet[K comparable, V any](m map[K]V) Set[K] {
return NewSet(maps.Keys(m)...)
}
// NewSubMapIntersect returns a sub-map of `m` containing only the keys found in
// both `m` and the `keys` slice.
func NewSubMapIntersect[K comparable, V any](m map[K]V, keys []K) map[K]V {
result := make(map[K]V)
for _, k := range keys {
v, ok := m[k]
if !ok {
continue
}
result[k] = v
}
return result
}
// NewSubMap creates a sub-map from a given map using specified keys. It errors
// if any of the keys is not found in the map.
func NewSubMap[K comparable, V any](m map[K]V, keys []K) (map[K]V, error) {
result := make(map[K]V, len(keys))
for _, k := range keys {
v, ok := m[k]
if !ok {
return nil, fmt.Errorf("NewSubMap: missing key %v", k)
}
result[k] = v
}
return result, nil
}