Modul:UniquePropertyValues

Aus Stadtsprachen
Wechseln zu:Navigation, Suche

Die Dokumentation für dieses Modul kann unter Modul:UniquePropertyValues/Doku erstellt werden

local p = {}

function p.getUniqueValues(propertyName)
    -- Handle case where propertyName is passed as a table
    if type(propertyName) == "table" then
        propertyName = propertyName[1]  -- Extract the first argument
    end
    
    -- Ensure the property name is provided
    if not propertyName or propertyName == "" then
        error("Property name required")
    end
    
    -- Query all pages with this property
    local ask = mw.smw.ask({
        "[[" .. propertyName .. "::+]]",  -- Select all pages where the property is defined
        "?" .. propertyName,              -- Ask for the value of the property
        "limit=500"                       -- Increase limit if necessary
    })
    
    -- Create a table to store unique values
    local uniqueValues = {}
    
    -- Iterate through results and collect unique values
    if ask then
        for _, result in ipairs(ask) do
            if result[propertyName] then
                -- Check if the result is a table (multiple values) or a string (single value)
                if type(result[propertyName]) == "table" then
                    for _, value in ipairs(result[propertyName]) do
                        -- Ensure that the value is not empty or nil
                        if value and value ~= "" then
                            uniqueValues[value] = true
                        end
                    end
                elseif type(result[propertyName]) == "string" then
                    -- Single value case
                    local value = result[propertyName]
                    if value and value ~= "" then
                        uniqueValues[value] = true
                    end
                end
            end
        end
    end
    
    -- Convert the unique values to an array and sort
    local valueArray = {}
    for value in pairs(uniqueValues) do
        table.insert(valueArray, value)
    end
    table.sort(valueArray)
    
    -- Return the array of unique values
    return valueArray
end

return p