-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathtransform.go
118 lines (106 loc) · 2.22 KB
/
transform.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
package contalgo
// Copy make a copy of slice a.
// Complexity: O(len(a)).
func Copy[T any](a []T) []T {
b := append([]T{}, a...)
return b
}
// Transform applies the function op to each element in slice a and fill it to slice b.
// The len(b) must not lesser than len(a).
// Complexity: O(len(a)).
func TransformTo[R any, T any](a []T, op func(T) R, b []R) {
if len(b) < len(a) {
panic("TransformTo: len(b) < len(a)")
}
for i, v := range a {
b[i] = op(v)
}
}
// Transform applies the function op to each element in slice a and set it back to the same place in a.
// Complexity: O(len(a)).
func Transform[T any](a []T, op func(T) T) {
for i, v := range a {
a[i] = op(v)
}
}
// Transform applies the function op to each element in slice a and return all the result as a slice.
// Complexity: O(len(a)).
func TransformCopy[R any, T any](a []T, op func(T) R) []R {
r := make([]R, 0, len(a))
for _, v := range a {
r = append(r, op(v))
}
return r
}
// Unique remove adjacent repeated elements from the input slice.
// return the processed slice, andthe origin slice is also changed.
// Complexity: O(len(a)).
func Unique[T comparable](a []T) []T {
if len(a) == 0 {
return a
}
i := 1
prev := a[0]
for _, v := range a[1:] {
if v != prev {
a[i] = v
i++
prev = v
}
}
return a[:i]
}
// Unique remove adjacent repeated elements from the input slice.
// return the processed slice, andthe origin slice is kept unchanged.
// Complexity: O(len(a)).
func UniqueCopy[T comparable](a []T) []T {
var r []T
if len(a) == 0 {
return r
}
for _, v := range a {
if len(r) > 0 && r[len(r)-1] == v {
continue
}
r = append(r, v)
}
return r
}
func Remove[T comparable](a []T, x T) []T {
j := 0
for _, v := range a {
if v != x {
a[j] = v
j++
}
}
return a[:j]
}
func RemoveCopy[T comparable](a []T, x T) []T {
r := make([]T, 0, len(a))
for _, v := range a {
if v != x {
r = append(r, v)
}
}
return r
}
func RemoveIf[T any](a []T, cond func(T) bool) []T {
j := 0
for _, v := range a {
if !cond(v) {
a[j] = v
j++
}
}
return a[:j]
}
func RemoveIfCopy[T any](a []T, cond func(T) bool) []T {
r := make([]T, 0, len(a))
for _, v := range a {
if !cond(v) {
r = append(r, v)
}
}
return r
}