-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.go
130 lines (101 loc) · 2.13 KB
/
vector.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 tl
// Vec defines a slice of type T.
type Vec[T any] []T
// MakeVec returns a vector of type T with the elements `elmnts`.
func MakeVec[T any](elmnts ...T) Vec[T] {
vc := Vec[T]{}
vc.Append(elmnts...)
return vc
}
// MakeVecSize returns a vector with size `size` and capacity `capacity`.
func MakeVecSize[T any](size, capacity int) Vec[T] {
return (Vec[T])(make([]T, size, capacity))
}
func (vc Vec[T]) Get(i int) T {
return vc[i]
}
func (vc *Vec[T]) Resize(n int) {
vc.Reserve(n)
*vc = (*vc)[:n]
}
func (vc *Vec[T]) Reserve(n int) {
if nSize := n - cap(*vc); nSize > 0 {
*vc = append((*vc)[:cap(*vc)], make([]T, nSize)...)
}
}
func (vc *Vec[T]) Append(elmnts ...T) {
*vc = append(*vc, elmnts...)
}
func (vc *Vec[T]) Push(elmnts ...T) {
*vc = append((*vc)[:len(elmnts)], *vc...)
copy(*vc, elmnts)
}
func (vc Vec[T]) Front() (opt OptionalPtr[T]) {
if len(vc) != 0 {
opt.Set(&vc[0])
}
return opt
}
func (vc Vec[T]) Back() (opt OptionalPtr[T]) {
if len(vc) != 0 {
opt.Set(&vc[len(vc)-1])
}
return
}
func (vc *Vec[T]) PopBack() (opt OptionalPtr[T]) {
if len(*vc) != 0 {
opt.Set(&(*vc)[len(*vc)-1])
*vc = (*vc)[:len(*vc)-1]
}
return
}
func (vc *Vec[T]) PopFront() (opt OptionalPtr[T]) {
if len(*vc) != 0 {
opt.Set(&(*vc)[0])
*vc = append((*vc)[:0], (*vc)[1:]...)
}
return
}
func (vc Vec[T]) Len() int {
return len(vc)
}
func (vc Vec[T]) Cap() int {
return cap(vc)
}
type CompareFunc[T any] func(T) bool
func (vc *Vec[T]) Filter(cmpFn CompareFunc[T]) (val T, erased bool) {
for i := 0; i < len(*vc); i++ {
if cmpFn((*vc)[i]) {
vc.DelByIndex(i)
i--
}
}
return
}
func (vc *Vec[T]) DelByIndex(i int) (val T, erased bool) {
if vc.Len() <= i {
return val, false
}
val = (*vc)[i]
*vc = append((*vc)[:i], (*vc)[i+1:]...)
return val, true
}
func (vc Vec[T]) Index(cmpFn CompareFunc[T]) int {
for i := range vc {
if cmpFn(vc[i]) {
return i
}
}
return -1
}
func (vc Vec[T]) Contains(cmpFn CompareFunc[T]) bool {
return vc.Index(cmpFn) >= 0
}
func (vc Vec[T]) Search(cmpFn CompareFunc[T]) (v T, ok bool) {
for i := range vc {
if cmpFn(vc[i]) {
return vc[i], true
}
}
return
}