forked from digisan/go-generics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.go
76 lines (66 loc) · 1.14 KB
/
queue.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
package gogenerics
import (
"fmt"
"strings"
)
type Queue[T any] []T
// *** Enqueue :
func (q *Queue[T]) Enqueue(items ...T) int {
*q = append(*q, items...)
return len(items)
}
// *** Len :
func (q *Queue[T]) Len() int {
return len(*q)
}
// *** Dequeue :
func (q *Queue[T]) Dequeue() (T, bool) {
if q.Len() > 0 {
first := (*q)[0]
*q = (*q)[1:]
return first, true
}
return *new(T), false
}
// *** Peek :
func (q *Queue[T]) Peek() (T, bool) {
if q.Len() > 0 {
return (*q)[0], true
}
return *new(T), false
}
// *** Clear :
func (q *Queue[T]) Clear() Queue[T] {
cp := q.Copy()
*q = Queue[T]{}
return cp
}
// *** Copy :
func (q *Queue[T]) Copy() Queue[T] {
tmp := make([]T, q.Len())
copy(tmp, *q)
return Queue[T](tmp)
}
// *** Sink :
func (q *Queue[T]) Sink() []T {
n := q.Len()
arr := make([]T, 0, n)
for {
if ele, ok := q.Dequeue(); ok {
arr = append(arr, ele)
} else {
break
}
}
return arr
}
// *** String :
func (q Queue[T]) String() string {
sep := ","
sb := strings.Builder{}
for _, ele := range q {
sb.WriteString(fmt.Sprintf("%v", ele))
sb.WriteString(sep)
}
return strings.TrimRight(sb.String(), sep)
}