Queue: document with comments

This commit is contained in:
Starbeamrainbowlabs 2021-08-04 21:11:47 +01:00
parent b7c3f21135
commit 7c7abf4509
Signed by: sbrl
GPG key ID: 1BE5172E637709C2

View file

@ -1,16 +1,22 @@
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
--- A Queue implementation, taken & adapted from https://www.lua.org/pil/11.4.html --- A Queue implementation
-- Taken & adapted from https://www.lua.org/pil/11.4.html
-- @submodule worldeditadditions.utils.queue -- @submodule worldeditadditions.utils.queue
-- @class
local Queue = {} local Queue = {}
Queue.__index = Queue Queue.__index = Queue
--- Creates a new queue instance.
-- @returns Queue
function Queue.new() function Queue.new()
local result = { first = 0, last = -1, items = {} } local result = { first = 0, last = -1, items = {} }
setmetatable(result, Queue) setmetatable(result, Queue)
return result return result
end end
--- Adds a new value to the end of the queue.
-- @param value any The new value to add to the end of the queue.
-- @returns number The index of the value that was added to the queue.
function Queue:enqueue(value) function Queue:enqueue(value)
local new_last = self.last + 1 local new_last = self.last + 1
self.last = new_last self.last = new_last
@ -18,6 +24,9 @@ function Queue:enqueue(value)
return new_last return new_last
end end
--- Determines whether a given value is present in this queue or not.
-- @param value any The value to check.
-- @returns bool Whether the given value exists in the queue or not.
function Queue:contains(value) function Queue:contains(value)
for i=self.first,self.last do for i=self.first,self.last do
if self.items[i] == value then if self.items[i] == value then
@ -27,14 +36,22 @@ function Queue:contains(value)
return false return false
end end
--- Returns whether the queue is empty or not.
-- @returns bool Whether the queue is empty or not.
function Queue:is_empty() function Queue:is_empty()
return self.first > self.last return self.first > self.last
end end
--- Removes the item with the given index from the queue.
-- Item indexes do not change as the items in a queue are added and removed.
-- @param number The index of the item to remove from the queue.
-- @returns nil
function Queue:remove_index(index) function Queue:remove_index(index)
self.items[index] = nil self.items[index] = nil
end end
--- Dequeues an item from the front of the queue.
-- @returns any|nil Returns the item at the front of the queue, or nil if no items are currently enqueued.
function Queue:dequeue() function Queue:dequeue()
if Queue.is_empty(self) then if Queue.is_empty(self) then
error("Error: The self is empty!") error("Error: The self is empty!")
@ -53,4 +70,5 @@ function Queue:dequeue()
return value return value
end end
return Queue return Queue