datatypes: add a Queue.last() method (#12987)

pull/12995/head
Hunam 2021-12-29 07:01:47 +01:00 committed by GitHub
parent 5e5529441c
commit 5607cfbd32
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 1 deletions

View File

@ -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)

View File

@ -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)