-
Notifications
You must be signed in to change notification settings - Fork 1
/
fp.go
88 lines (77 loc) · 2.12 KB
/
fp.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package gfn
/* @example Map
gfn.Map([]int{1, 2, 3}, func(i int) string { return i+1 })
// []int{2, 3, 4}
gfn.Map([]int{1, 2, 3}, func(i int) string {
return strconv.Itoa(i)
})
// []string{"1", "2", "3"}
*/
// Map returns a new array with the results of calling the mapper function on each element.
// No MapKV because I don't know what to return, an array or a map? Instead, please use ForEachKV.
func Map[T any, R any](array []T, mapper func(T) R) []R {
result := make([]R, len(array))
for i, v := range array {
result[i] = mapper(v)
}
return result
}
/* @example Filter
array := []int{1, 2, 3, 4, 5, 6}
gfn.Filter(array, func(i int) bool { return i%2 == 0 })
// []int{2, 4, 6}
*/
// Filter returns a new array containing elements of the original array
// that satisfy the provided function.
func Filter[T any](array []T, filter func(T) bool) []T {
result := make([]T, 0)
for _, v := range array {
if filter(v) {
result = append(result, v)
}
}
return result
}
/* @example FilterKV
m := map[int]string{1: "a", 2: "b", 3: "c"}
gfn.FilterKV(m, func(k int, v string) bool {
return k == 1 || v == "c"
})
// map[int]string{1: "a", 3: "c"}
*/
// FilterKV returns a new map containing elements of the original map
// that satisfy the provided function.
func FilterKV[K comparable, V any](m map[K]V, fn func(K, V) bool) map[K]V {
return Select(m, fn)
}
/* @example Reduce
gfn.Reduce([]int{1, 2, 3}, 0, func(a, b int) int {
return a + b
})
// 6
*/
// Reduce executes a reducer function on each element of the array,
// resulting in a single output value.
func Reduce[T any, R any](array []T, init R, fn func(R, T) R) R {
result := init
for _, v := range array {
result = fn(result, v)
}
return result
}
/* @example ReduceKV
m := map[string]int{"a": 1, "b": 2, "c": 3}
total := gfn.ReduceKV(m, 0, func(value int, k string, v int) int {
return value + v
})
// 6
*/
// ReduceKV executes a reducer function on each element of the map,
// resulting in a single output value.
func ReduceKV[K comparable, V any, R any](m map[K]V, init R, fn func(R, K, V) R) R {
result := init
for k, v := range m {
result = fn(result, k, v)
}
return result
}