-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap_transform.go
More file actions
49 lines (46 loc) · 1.43 KB
/
Copy pathmap_transform.go
File metadata and controls
49 lines (46 loc) · 1.43 KB
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
package gofu
// ToSlice converts the map to a Slice using a mapper fn. [ Immutable ] [ time: O(n); space: O(n)]
//
// Example:
//
// gofu.Map[string, int]{"a": 1, "b": 2}.
// ToSlice(func(k string, v int) string { return k + strconv.Itoa(v) })
// // Slice[string]{"a1", "b2"} (order not guaranteed)
func (m Map[K, V]) ToSlice[S any](fn func(K, V) S) Slice[S] {
result := make(Slice[S], 0, len(m))
for k, v := range m {
result = append(result, fn(k, v))
}
return result
}
// Map transforms keys and values of the map. [ Immutable ] [ time: O(n); space: O(n)]
// If multiple entries map to the same new key, the last one wins.
//
// Example:
//
// gofu.Map[string, int]{"a": 1, "b": 2}.
// Map(func(k string, v int) (string, string) {
// return k, strconv.Itoa(v)
// })
// // Map[string]string{"a": "1", "b": "2"}
func (m Map[K, V]) Map[K2 comparable, V2 any](fn func(K, V) (K2, V2)) Map[K2, V2] {
result := make(Map[K2, V2], len(m))
for k, v := range m {
k2, v2 := fn(k, v)
result[k2] = v2
}
return result
}
// Reduce combines key-value pairs using fn, starting from initial. [ Immutable ] [ time: O(n); space: O(1)]
//
// Example:
//
// gofu.Map[string, int]{"a": 10, "b": 20, "c": 30}.
// Reduce(0, func(acc int, k string, v int) int { return acc + v }) // 60
func (m Map[K, V]) Reduce[R any](initial R, fn func(R, K, V) R) R {
result := initial
for k, v := range m {
result = fn(result, k, v)
}
return result
}