Module:Iterator

From the Tesseract Wiki, the wiki for all things Marvel Cinematic Universe
Jump to navigation Jump to search

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

-- <nowiki>
local checkType = require('libraryUtil').checkType
local p = {}

function p.opairs(t)
	checkType('Module:Iterator.opairs', 1, t, 'table')
    local orderedKeys = {}
    local i = 1

    for key in pairs( t ) do
        orderedKeys[i] = key
        i = i + 1
    end

    local function sortFunc(lhs, rhs)
        if type(lhs) == type(rhs) then
            return lhs < rhs
        else
            local order = {
                number = 1,
                string = 2,
                table = 3,
                ['function'] = 4,
            }
            return order[type(lhs)] < order[type(rhs)]
        end
    end

    table.sort(orderedKeys, sortFunc)

    i = 0
    return function()
        i = i + 1
        return orderedKeys[i], t[orderedKeys[i]]
    end
end

function p.spairs(t)
	checkType('Module:Iterator.spairs', 1, t, 'table')
    local function iter(t, k)
        local nextKey, nextVal = next(t, k)
        while nextKey ~= nil and type(nextKey) ~= "string" do
            nextKey, nextVal = next(t, nextKey)
        end
        return nextKey, nextVal
    end

    return iter, t, nil
end

function p.ospairs(t)
	checkType('Module:Iterator.ospairs', 1, t, 'table')
    local orderedKeys = {}
    local i = 1

    for key in pairs(t) do
        if type(key) == "string" then
            orderedKeys[i] = key
            i = i + 1
        end
    end

    table.sort(orderedKeys)

    i = 0

    return function()
        i = i + 1
        return orderedKeys[i], t[orderedKeys[i]]
    end
end

function p.sortedPairs(t, func)
    checkType('Module:Iterator.sortedPairs', 1, t, 'table')
    checkType('Module:Iterator.sortedPairs', 2, func, 'function', true)
    local elements = {}

    for k, v in pairs(t) do
        table.insert(elements, {key=k, value=v})
    end

    table.sort(elements, function(lhs, rhs) return func(lhs.value, rhs.value) end)

    local function it(t, i)
    	i = i + 1
    	if t[i] ~= nil then
    		return i, t[i].key, t[i].value
		end
	end
	
	return it, elements, 0
end

return p
--</nowiki>