queue.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package fn
  2. // Queue is a generic queue implementation.
  3. type Queue[T any] struct {
  4. items []T
  5. }
  6. // NewQueue creates a new Queue.
  7. func NewQueue[T any](startingItems ...T) Queue[T] {
  8. return Queue[T]{
  9. items: startingItems,
  10. }
  11. }
  12. // Enqueue adds one or more an items to the end of the Queue.
  13. func (q *Queue[T]) Enqueue(value ...T) {
  14. q.items = append(q.items, value...)
  15. }
  16. // Dequeue removes an element from the front of the Queue. If there're no items
  17. // in the queue, then None is returned.
  18. func (q *Queue[T]) Dequeue() Option[T] {
  19. if len(q.items) == 0 {
  20. return None[T]()
  21. }
  22. value := q.items[0]
  23. q.items = q.items[1:]
  24. return Some(value)
  25. }
  26. // Peek returns the first item in the queue without removing it. If the queue
  27. // is empty, then None is returned.
  28. func (q *Queue[T]) Peek() Option[T] {
  29. if q.IsEmpty() {
  30. return None[T]()
  31. }
  32. return Some(q.items[0])
  33. }
  34. // IsEmpty returns true if the Queue is empty
  35. func (q *Queue[T]) IsEmpty() bool {
  36. return len(q.items) == 0
  37. }
  38. // Size returns the number of items in the Queue
  39. func (q *Queue[T]) Size() int {
  40. return len(q.items)
  41. }