File tree Expand file tree Collapse file tree 2 files changed +91
-0
lines changed
Expand file tree Collapse file tree 2 files changed +91
-0
lines changed Original file line number Diff line number Diff line change 1+ package queue
2+
3+ // Queue is generic FIFO queue.
4+ type Queue [E any ] struct {
5+ s []E
6+ }
7+
8+ // New creates a new queue backed by a slice.
9+ func New [E any ]() * Queue [E ] {
10+ return & Queue [E ]{}
11+ }
12+
13+ // Push adds an element to last position of the queue.
14+ func (q * Queue [E ]) Push (e E ) {
15+ q .s = append (q .s , e )
16+ }
17+
18+ // Pop removes and returns the first element from the queue.
19+ // Pop panics if the queue is empty.
20+ func (q * Queue [E ]) Pop () E {
21+ current := q .s [0 ]
22+
23+ var zero E
24+ q .s [0 ] = zero
25+ q .s = q .s [1 :]
26+
27+ return current
28+ }
29+
30+ // Peek returns the first element in the queue.
31+ // Peek panics if the queue is empty.
32+ func (q * Queue [E ]) Peek () E {
33+ return q .s [0 ]
34+ }
35+
36+ // Len returns the number of elements in the queue.
37+ func (q * Queue [E ]) Len () int {
38+ return len (q .s )
39+ }
40+
41+ // Empty returns true if the queue is empty.
42+ func (q * Queue [E ]) Empty () bool {
43+ return len (q .s ) == 0
44+ }
45+
46+ // Clear removes all elements from the queue.
47+ func (q * Queue [E ]) Clear () {
48+ clear (q .s )
49+ q .s = q .s [:0 ]
50+ }
51+
52+ // Slice returns the underlying slice.
53+ // The queue retains the returned slice, so altering the slice may break the invariants and invalidate the queue.
54+ func (q * Queue [E ]) Slice () []E {
55+ return q .s
56+ }
Original file line number Diff line number Diff line change 1+ package queue
2+
3+ import (
4+ "testing"
5+
6+ "github.com/gravitton/assert"
7+ )
8+
9+ func TestQueue (t * testing.T ) {
10+ q := New [int ]()
11+
12+ assert .Equal (t , q .Len (), 0 )
13+ assert .True (t , q .Empty ())
14+
15+ q .Push (2 )
16+ q .Push (3 )
17+ q .Push (1 )
18+
19+ assert .Equal (t , q .Len (), 3 )
20+ assert .False (t , q .Empty ())
21+
22+ assert .Equal (t , q .Peek (), 2 )
23+ assert .Equal (t , q .Len (), 3 )
24+
25+ assert .Equal (t , q .Pop (), 2 )
26+ assert .Equal (t , q .Len (), 2 )
27+
28+ s := q .Slice ()
29+ assert .Equal (t , s , []int {3 , 1 })
30+ q .Clear ()
31+
32+ assert .Equal (t , s , []int {0 , 0 })
33+ assert .Equal (t , q .Len (), 0 )
34+ assert .True (t , q .Empty ())
35+ }
You can’t perform that action at this time.
0 commit comments