Module:ListSorter

From Uncyclopedia, the content-free encyclopedia
Jump to navigation Jump to search

local p = {}

function p.sort(frame)
    -- Get the input string (the list of users)
    local input = frame.args[1] or ""
    
    -- 1. Remove newlines/carriage returns to prevent formatting breaks
    input = input:gsub("[\r\n]", " ")
    
    -- 2. Split the list by the bullet character
    -- (Note: We use mw.text.split for safe unicode handling)
    local items = mw.text.split(input, "•")
    
    -- 3. Trim whitespace from each item so sorting is clean
    for i, v in ipairs(items) do
        items[i] = mw.text.trim(v)
    end
    
    -- 4. The Sorting Function
    table.sort(items, function(a, b)
        -- We strip the '{{u|' and '}}' and extra comments for the comparison only
        -- This ensures {{u|Z}} sorts after {{u|A}} correctly
        local cleanA = a:gsub("{{u|", ""):gsub("}}", ""):gsub("%b()", ""):lower() -- removes (text in parens) for sorting
        local cleanB = b:gsub("{{u|", ""):gsub("}}", ""):gsub("%b()", ""):lower()
        return cleanA < cleanB
    end)
    
    -- 5. Filter out empty entries (caused by trailing bullets)
    local output = {}
    for _, v in ipairs(items) do
        if v ~= "" then
            table.insert(output, v)
        end
    end
    
    -- 6. Join them back together with the bullet
    return table.concat(output, " • ")
end

return p