File: maps.go

package info (click to toggle)
golang-github-jesseduffield-generics 0.0~git20250517.b0b4a53-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 204 kB
  • sloc: makefile: 2
file content (53 lines) | stat: -rw-r--r-- 1,303 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package maps

func Keys[Key comparable, Value any](m map[Key]Value) []Key {
	keys := make([]Key, 0, len(m))
	for key := range m {
		keys = append(keys, key)
	}
	return keys
}

func Values[Key comparable, Value any](m map[Key]Value) []Value {
	values := make([]Value, 0, len(m))
	for _, value := range m {
		values = append(values, value)
	}
	return values
}

func TransformValues[Key comparable, Value any, NewValue any](
	m map[Key]Value, fn func(Value) NewValue,
) map[Key]NewValue {
	output := make(map[Key]NewValue, len(m))
	for key, value := range m {
		output[key] = fn(value)
	}
	return output
}

func TransformKeys[Key comparable, Value any, NewKey comparable](m map[Key]Value, fn func(Key) NewKey) map[NewKey]Value {
	output := make(map[NewKey]Value, len(m))
	for key, value := range m {
		output[fn(key)] = value
	}
	return output
}

func MapToSlice[Key comparable, Value any, Mapped any](m map[Key]Value, f func(Key, Value) Mapped) []Mapped {
	output := make([]Mapped, 0, len(m))
	for key, value := range m {
		output = append(output, f(key, value))
	}
	return output
}

func Filter[Key comparable, Value any](m map[Key]Value, f func(Key, Value) bool) map[Key]Value {
	output := map[Key]Value{}
	for key, value := range m {
		if f(key, value) {
			output[key] = value
		}
	}
	return output
}