Anonymous

Module:FunList: Difference between revisions

From Melvor Idle
no edit summary
(First version (wip))
 
No edit summary
Line 11: Line 11:
-- Private fields
-- Private fields
local mytable = tbl
local mytable = tbl
-- Private functions.
local function getElementAtIndex(index)
assert(tonumber(index))
local ix = tonumber(index)
local i = 0
if ix >= 0 then
for _, v in pairs(mytable) do
i = i + 1
if i == ix then
return true, v
end
end
end
return false, nil
end


-- Public functions
-- Determines whether all elements of a sequence satisfy a condition.
-- Determines whether all elements of a sequence satisfy a condition.
function funlist.all(predicate)
function funlist.all(predicate)
Line 63: Line 81:
end
end
return count
return count
end
-- Returns the element at a specified index in a sequence.
function funlist.itemAt(index)
local found, item = getElementAtIndex(index)
if found == true then
return item
end
error('Index out of range')
end
-- Returns the element at a specified index in a sequence or a default value if the index is out of range.
function funlist.itemAtOrDefault(index, defaultItem)
local found, item = getElementAtIndex(index)
if found == true then
return item
end
return defaultItem
end
-- Returns the first element of a sequence.
function funlist.first()
for _, v in pairs(mytable) do
return v
end
error('No items in sequence.')
end
-- Returns the first element of a sequence, or a default value if no element is found.
function funlist.firstOrDefault(defaultItem)
for _, v in pairs(mytable) do
return v
end
return defaultItem
end
-- Returns the last element of a sequence.
function funlist.last()
if funlist.any() == false then
error('Sequence contains no items.')
end
local last = nil
for _, v in pairs(mytable) do
last = v
end
return last
end
-- Returns the last element of a sequence, or a default value if no element is found.
function funlist.lastOrDefault(defaultItem)
if funlist.any() == false then
return defaultItem
end
local last = nil
for _, v in pairs(mytable) do
last = v
end
return last
end
end
2,875

edits