Module:FunList/TableEnumerator

From Melvor Idle
< Module:FunList
Revision as of 19:57, 26 July 2024 by Ricewind (talk | contribs) (Created page with "---A lightweight enumerator for tables in array form. ---@class ArrayEnumerator : Enumerator ---@field _tbl table ---@field current any ---@field index integer local ArrayEnumerator = {} ArrayEnumerator.__index = ArrayEnumerator function ArrayEnumerator.new(tbl) assert(tbl) local self = setmetatable({}, ArrayEnumerator) self._tbl = tbl self.current = nil self.index = 0 return self end function ArrayEnumerator:moveNext() local index = self.i...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation for this module may be created at Module:FunList/TableEnumerator/doc

---A lightweight enumerator for tables in array form.
---@class ArrayEnumerator : Enumerator
---@field _tbl table
---@field current any
---@field index integer
local ArrayEnumerator = {}
ArrayEnumerator.__index = ArrayEnumerator

function ArrayEnumerator.new(tbl)
    assert(tbl)
    local self = setmetatable({}, ArrayEnumerator)
    self._tbl = tbl
    self.current = nil
    self.index = 0

    return self
end

function ArrayEnumerator:moveNext()
    local index = self.index + 1
    local next = self._tbl[index]
    self.index = index
    self.current = next
    return next ~= nil
end

function ArrayEnumerator:finalize()
end

---A lightweight enumerator for tables in hash set form.
---@class HashTableEnumerator : Enumerator
---@field _tbl table
---@field current any
---@field index any
local HashTableEnumerator = {}
HashTableEnumerator.__index = HashTableEnumerator

function HashTableEnumerator.new(tbl)
    assert(tbl)
    local self = setmetatable({}, HashTableEnumerator)
    self._tbl = tbl

    return self
end

function HashTableEnumerator:moveNext()
    local key = self.index
    key = next(self._tbl, key)
    self.index = key
    if key ~= nil then
        self.current = self._tbl[key]
        return true
    end
    return false
end

function HashTableEnumerator:finalize()
end

local TableEnumerator = {}
---Creates a lightweight enumerator for the Lua table type.
---@param tbl table
---@param isArray boolean
---@return Enumerator
function TableEnumerator.create(tbl, isArray)
    assert(tbl, 'Table cannot be nil.')
    if isArray == nil then isArray = false end

    if isArray == true then
        return ArrayEnumerator.new(tbl)
    else
        return HashTableEnumerator.new(tbl)
    end
end

---Creates a lightweight enumerator for the Lua table type.
---@param tbl table
---@return Enumerator
function TableEnumerator.createForArray(tbl)
    assert(tbl, 'Table cannot be nil.')
    return ArrayEnumerator.new(tbl)
end

---Creates a lightweight enumerator for the Lua table type.
---@param tbl table
---@return Enumerator
function TableEnumerator.createForHash(tbl)
    assert(tbl, 'Table cannot be nil.')
    return HashTableEnumerator.new(tbl)
end

return TableEnumerator