-
Notifications
You must be signed in to change notification settings - Fork 0
/
mr.go
130 lines (116 loc) · 2.43 KB
/
mr.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package mr
import "strings"
func Map[T any, R any](ts []T, f func(T) R) []R {
nt := make([]R, 0, len(ts))
for _, t := range ts {
nt = append(nt, f(t))
}
return nt
}
func Reduce[T any](ts []T, f func(T, T) T, init T) T {
t := init
for _, tt := range ts {
t = f(t, tt)
}
return t
}
func Filter[T any](ts []T, f func(T) bool) []T {
nt := make([]T, 0, len(ts))
for _, t := range ts {
if f(t) {
nt = append(nt, t)
}
}
return nt
}
func ToMap[T any, KEY comparable](ts []T, f func(T) KEY) map[KEY]T {
m := make(map[KEY]T, len(ts))
for _, v := range ts {
m[f(v)] = v
}
return m
}
func Unique[T any, KEY comparable](ts []T, f func(T) KEY) []T {
m := make(map[KEY]struct{}, len(ts))
nt := make([]T, 0, len(ts))
for _, t := range ts {
k := f(t)
if _, ok := m[k]; ok {
continue
}
nt = append(nt, t)
m[k] = struct{}{}
}
return nt
}
func Diff[T any, KEY comparable](ts1, ts2 []T, f func(T) KEY) []T {
nt := make([]T, 0, len(ts1))
ts2Map := ToMap(ts2, f)
for _, t := range ts1 {
if _, ok := ts2Map[f(t)]; !ok {
nt = append(nt, t)
}
}
return nt
}
func Intersect[T any, KEY comparable](ts1, ts2 []T, f func(T) KEY) []T {
nt := make([]T, 0, len(ts1))
ts2Map := ToMap(ts2, f)
for _, t := range ts1 {
if _, ok := ts2Map[f(t)]; ok {
nt = append(nt, t)
}
}
return nt
}
func Merge[T any, KEY comparable](ts1, ts2 []T, f func(T) KEY) []T {
nt := make([]T, 0, len(ts1)+len(ts2))
ts2Map := ToMap(ts2, f)
replaced := make(map[KEY]struct{}, len(ts2))
for _, t := range ts1 {
if v, ok := ts2Map[f(t)]; ok {
nt = append(nt, v)
replaced[f(t)] = struct{}{}
} else {
nt = append(nt, t)
}
}
for _, t := range ts2 {
if _, ok := replaced[f(t)]; !ok {
nt = append(nt, t)
}
}
return nt
}
func Contains[T any, KEY comparable](ts []T, t T, f func(T) KEY) bool {
tsMap := ToMap(ts, f)
_, ok := tsMap[f(t)]
return ok
}
func Paginate[T any](list []T, page, size int) []T {
offset := (page - 1) * size
if offset >= len(list) {
return make([]T, 0)
}
if offset+size >= len(list) {
return list[offset:]
}
return list[offset : offset+size]
}
func Join[T any](list []T, sep string, f func(T) string) string {
var builder strings.Builder
for i := 0; i < len(list); i++ {
if i > 0 {
builder.WriteString(sep)
}
builder.WriteString(f(list[i]))
}
return builder.String()
}
func Keys[T any, KEY comparable](data map[KEY]T) []KEY {
var d []KEY
for k := range data {
d = append(d, k)
}
return d
}