gods/mapx/main.go

59 lines
1 KiB
Go
Raw Normal View History

2022-11-25 16:30:51 +03:00
package mapx
2023-07-11 20:01:04 +03:00
import (
"fmt"
)
2023-07-09 11:39:35 +03:00
// The package implements some more specific
// map structures for special uses.
2023-07-21 19:00:09 +03:00
// Implemented mostly to be embedded to other structures.
2023-07-11 20:01:04 +03:00
// General map type, wrap for the built-in one.
type Map[K comparable, V any] map[K] V
// Returns new basic map.
func New[K comparable, V any]() Map[K, V] {
return make(Map[K, V])
}
// Returns slice of keys of the map.
func (m Map[K, V]) Keys() []K {
2022-11-25 16:30:51 +03:00
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
2023-07-11 20:01:04 +03:00
// Returns slice of values of the map.
func (m Map[K, V]) Values(sm map[K] V) []V {
2022-11-25 16:30:51 +03:00
r := make([]V, 0, len(m))
for _, v := range m {
r = append(r, v)
}
return r
}
2023-07-11 20:01:04 +03:00
// Checks if the map contains the key.
func (m Map[K, V]) Has(k K) bool {
_, ok := m[k]
return ok
}
2022-11-25 16:30:51 +03:00
2023-07-11 20:01:04 +03:00
// Sets the new value by key or resets if it exists.
func (m Map[K, V]) Set(k K, v V) {
m[k] = v
}
// Returns the value by key. Panics if there is no such key.
func (m Map[K, V]) Get(k K) V {
v, ok := m[k]
if !ok {
panic(fmt.Sprintf("there is no such key '%v'", k))
}
return v
2022-11-25 16:30:51 +03:00
}