diff --git a/vlib/datatypes/queue.v b/vlib/datatypes/queue.v index ed1317b38f..8aab6ac3b0 100644 --- a/vlib/datatypes/queue.v +++ b/vlib/datatypes/queue.v @@ -15,11 +15,16 @@ pub fn (queue Queue) len() int { return queue.elements.len() } -// peek returns the head of the queue +// peek returns the head of the queue (first element added) pub fn (queue Queue) peek() ?T { return if !queue.is_empty() { queue.elements.first() ? } else { error('Queue is empty') } } +// last returns the tail of the queue (last element added) +pub fn (queue Queue) last() ?T { + return if !queue.is_empty() { queue.elements.last() ? } else { error('Queue is empty') } +} + // push adds an element to the tail of the queue pub fn (mut queue Queue) push(item T) { queue.elements.push(item) diff --git a/vlib/datatypes/queue_test.v b/vlib/datatypes/queue_test.v index 98cadc641b..2bfc23a8aa 100644 --- a/vlib/datatypes/queue_test.v +++ b/vlib/datatypes/queue_test.v @@ -27,6 +27,17 @@ fn test_peek() ? { assert false } +fn test_last() ? { + mut queue := Queue{} + queue.push(1) + assert queue.last() ? == 1 + queue.push(2) + assert queue.last() ? == 2 + queue = Queue{} + queue.last() or { return } + assert false +} + fn test_push() ? { mut queue := Queue{} queue.push(1)