diff --git a/linear/queue.go b/linear/queue.go new file mode 100644 index 0000000..5257f19 --- /dev/null +++ b/linear/queue.go @@ -0,0 +1,71 @@ +package linear + +import ( + "errors" +) + +// Queue []Type{} -> creates a Queue with no fixed size +// Implemented as slice +type Queue[T any] struct { + capacity uint8 + container []T +} + +// QueueFixed -> QueueFixed[Type](size) creates a Queue with no fixed size +func QueueFixed[T any](value uint8) *Queue[T] { + return &Queue[T]{ + capacity: value, + container: make([]T, 0, value), + } +} + +// Add() -> enqeues an item, returns err if queue if full +func (q *Queue[T]) Add(item T) error { + if q.capacity > 0 && q.capacity <= uint8(len(q.container)) { + return errors.New("Queue full") + } + + q.container = append(q.container, item) + return nil +} + +// Peek() -> returns the upcoming item +func (q *Queue[T]) Peek() (T, bool) { + if len(q.container) <= 0 { + var zero T + return zero, false + } + + return q.container[0], true +} + +// Pull() -> returns the upcoming item and removes it from Queue +func (q *Queue[T]) Pull() (T, error) { + if len(q.container) <= 0 { + var zero T + return zero, errors.New("Queue is empty") + } + + upcoming := q.container[0] + q.container = q.container[1:] + + return upcoming, nil +} + +// Cull() -> removes the last item , returns it and err +func (q *Queue[T]) Cull() (T, error) { + if len(q.container) <= 0 { + var zero T + return zero, errors.New("Queue is empty") + } + + last := q.container[len(q.container)-1] + q.container = q.container[0 : len(q.container)-1] + + return last, nil +} + +// Size() -> returns size of queue +func (q *Queue[T]) Size() int { + return len(q.container) +} diff --git a/linear/stack.go b/linear/stack.go index e820aa2..e421239 100644 --- a/linear/stack.go +++ b/linear/stack.go @@ -1,4 +1,4 @@ -package stack +package linear import ( "errors" @@ -12,12 +12,10 @@ type Stack[T any] struct { // StackFixed -> creates Stack with a fixed size func StackFixed[T any](value int) *Stack[T] { - return &Stack[T]{ Capacity: value, Container: make([]T, 0, value), } - } // Push -> Appends value to stack returns error @@ -33,7 +31,6 @@ func (s *Stack[T]) Push(value T) error { // Pop -> returns value,error and removes last index func (s *Stack[T]) Pop() (T, error) { - var zero T if len(s.Container) <= 0 { diff --git a/linear/stack_test.go b/linear/stack_test.go index 4b37b5b..b041abd 100644 --- a/linear/stack_test.go +++ b/linear/stack_test.go @@ -1,4 +1,4 @@ -package stack +package linear import ( "testing" @@ -13,5 +13,4 @@ func TestPush(t *testing.T) { if len(s.Container) != 3 { t.Errorf("expected 2 items, got %d", len(s.Container)) } - }