| 1 | package maps |
| 2 | |
| 3 | func Keys[Key comparable, Value any](m map[Key]Value) []Key { |
| 4 | keys := make([]Key, 0, len(m)) |
| 5 | for key := range m { |
| 6 | keys = append(keys, key) |
| 7 | } |
| 8 | return keys |
| 9 | } |
| 10 | |
| 11 | func Values[Key comparable, Value any](m map[Key]Value) []Value { |
| 12 | values := make([]Value, 0, len(m)) |
| 13 | for _, value := range m { |
| 14 | values = append(values, value) |
| 15 | } |
| 16 | return values |
| 17 | } |
| 18 | |
| 19 | func TransformValues[Key comparable, Value any, NewValue any]( |
| 20 | m map[Key]Value, fn func(Value) NewValue, |
| 21 | ) map[Key]NewValue { |
| 22 | output := make(map[Key]NewValue, len(m)) |
| 23 | for key, value := range m { |
| 24 | output[key] = fn(value) |
| 25 | } |
| 26 | return output |
| 27 | } |
| 28 | |
| 29 | func TransformKeys[Key comparable, Value any, NewKey comparable](m map[Key]Value, fn func(Key) NewKey) map[NewKey]Value { |
| 30 | output := make(map[NewKey]Value, len(m)) |
| 31 | for key, value := range m { |
| 32 | output[fn(key)] = value |
| 33 | } |
| 34 | return output |
| 35 | } |
| 36 | |
| 37 | func MapToSlice[Key comparable, Value any, Mapped any](m map[Key]Value, f func(Key, Value) Mapped) []Mapped { |
| 38 | output := make([]Mapped, 0, len(m)) |
| 39 | for key, value := range m { |
| 40 | output = append(output, f(key, value)) |
| 41 | } |
| 42 | return output |
| 43 | } |
| 44 | |
| 45 | func Filter[Key comparable, Value any](m map[Key]Value, f func(Key, Value) bool) map[Key]Value { |
| 46 | output := map[Key]Value{} |
| 47 | for key, value := range m { |
| 48 | if f(key, value) { |
| 49 | output[key] = value |
| 50 | } |
| 51 | } |
| 52 | return output |
| 53 | } |