Skip to content

Commit dbd4607

Browse files
committed
feat(Queue): implement write-read item stream
1 parent 6a782af commit dbd4607

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

queue.go

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package fungi
2+
3+
import "io"
4+
5+
// Q is a clever data structure that implements Stream and allows item enqueue
6+
// operation.
7+
type Q[T any] struct {
8+
items []T
9+
}
10+
11+
// Queue is a default constructor for Q.
12+
func Queue[T any]() *Q[T] {
13+
return QueueOf[T]()
14+
}
15+
16+
// QueueOf allows you to initialise a queue with some elements.
17+
func QueueOf[T any](items ...T) *Q[T] {
18+
return &Q[T]{
19+
items: items,
20+
}
21+
}
22+
23+
// Add some items to the queue.
24+
func (q *Q[T]) Add(items ...T) {
25+
q.items = append(q.items, items...)
26+
}
27+
28+
// Next item from the queue or error if it's empty.
29+
func (q *Q[T]) Next() (item T, err error) {
30+
if len(q.items) == 0 {
31+
err = io.EOF
32+
return
33+
}
34+
item = q.items[0]
35+
q.items = q.items[1:]
36+
return
37+
}

queue_test.go

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package fungi
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestQueue(t *testing.T) {
10+
slice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
11+
queue := Queue[int]()
12+
for _, i := range slice {
13+
queue.Add(i)
14+
}
15+
odds := Filter(func(i int) bool { return i%2 != 0 })
16+
sum := Reduce(func(i, j int) int { return i + j }, 0)
17+
result, err := sum(odds(queue))
18+
assert.NoError(t, err)
19+
assert.Equal(t, 25, result)
20+
}

0 commit comments

Comments
 (0)