Module:FunList
From Melvor Idle
Documentation for this module may be created at Module:FunList/doc
local funlist = {}
funlist.__index = funlist
-- Constructor
function funlist.new(tbl)
assert(type(tbl) == 'table')
assert(tbl ~= nil)
local self = setmetatable({}, funlist)
-- Private fields
local mytable = tbl
-- Determines whether all elements of a sequence satisfy a condition.
function funlist.all(predicate)
assert(predicate)
for _, v in pairs(mytable) do
if predicate(v) == false then
return false
end
end
return true
end
-- Determines whether any element of a sequence exists or satisfies a condition.
function funlist.any(predicate)
if predicate then
for _, v in pairs(mytable) do
if predicate(v) == true then
return true
end
end
else
for _, _ in pairs(mytable) do
return true
end
end
return false
end
-- Appends a value to the end of the sequence.
function funlist.append(item)
assert(item)
table.insert(mytable, item)
end
-- Determines whether a sequence contains a specified element.
function funlist.contains(item)
assert(item)
for _, v in pairs(mytable) do
if funlist.isEqual(v, item) == true then
return true
end
end
return false
end
-- Returns the number of elements in a sequence.
function funlist.count()
local count = 0
for _, _ in pairs(mytable) do
count = count + 1
end
return count
end
return self
end
-- Helper function to check if objects are equal.
function funlist.isEqual(obj1, obj2)
local type1 = type(obj1)
local type2 = type(obj2)
if type1 ~= type2 then
return false
end
if type1 == "number" or type1 == "string" or type1 == "boolean" then
return obj1 == obj2
elseif type1 == "table" then
if #obj1 ~= #obj2 then
return false
end
for k, v in pairs(obj1) do
if not isEqual(v, obj2[k]) then
return false
end
end
return true
else
return obj1 == obj2
end
end
return funlist