Skip to content

Commit

Permalink
datatypes: add a Queue.last() method (#12987)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hunam6 committed Dec 29, 2021
1 parent 5e55294 commit 5607cfb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
7 changes: 6 additions & 1 deletion vlib/datatypes/queue.v
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,16 @@ pub fn (queue Queue<T>) 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<T>) 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<T>) 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<T>) push(item T) {
queue.elements.push(item)
Expand Down
11 changes: 11 additions & 0 deletions vlib/datatypes/queue_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ fn test_peek() ? {
assert false
}

fn test_last() ? {
mut queue := Queue<int>{}
queue.push(1)
assert queue.last() ? == 1
queue.push(2)
assert queue.last() ? == 2
queue = Queue<int>{}
queue.last() or { return }
assert false
}

fn test_push() ? {
mut queue := Queue<int>{}
queue.push(1)
Expand Down

0 comments on commit 5607cfb

Please sign in to comment.