-
Notifications
You must be signed in to change notification settings - Fork 0
/
slices.go
65 lines (56 loc) · 1012 Bytes
/
slices.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
package btree
// helper functions for slices
func IndexOf[V comparable](v V, s []V) int {
for i, e := range s {
if v == e {
return i
}
}
return -1
}
func InsertAtIndex[V any](v V, s []V, index int) []V {
var ns []V
if index > 0 {
ns = append(ns, s[:index]...)
}
ns = append(ns, v)
if index < len(s) {
ns = append(ns, s[index:]...)
}
return ns
}
func RemoveAtIndex[V any](s []V, index int) []V {
var ns []V
if index > 0 {
ns = append(ns, s[:index]...)
}
if index+1 < len(s) {
ns = append(ns, s[index+1:]...)
}
return ns
}
type StackSlice[V any] []V
func (s *StackSlice[V]) Push(v V) {
*s = append(*s, v)
}
func (s *StackSlice[V]) Pop() (V, bool) {
var v V
if s.IsEmpty() {
return v, false
}
last := len(*s) - 1
v = (*s)[last]
*s = (*s)[:last]
return v, true
}
func (s *StackSlice[V]) Peek() (V, bool) {
var v V
if s.IsEmpty() {
return v, false
}
last := len(*s) - 1
return (*s)[last], true
}
func (s *StackSlice[V]) IsEmpty() bool {
return len(*s) == 0
}