Module:RarityHandler: Difference between revisions

No edit summary
No edit summary
(2 intermediate revisions by the same user not shown)
Line 5: Line 5:
     if not rarity or type(rarity) ~= "string" then return nil end
     if not rarity or type(rarity) ~= "string" then return nil end
     rarity = mw.text.trim(rarity)
     rarity = mw.text.trim(rarity)
    -- Strip leading ~
     if rarity:sub(1, 1) == "~" then
     if rarity:sub(1, 1) == "~" then
         rarity = rarity:sub(2)
         rarity = rarity:sub(2)
     end
     end
    -- Strip commas
    rarity = rarity:gsub(",", "")
     return rarity
     return rarity
end
end


function p.getSortValue(frame)
function p.getSortValue(frame)
     local raw = frame.args[1]
     local rarity = frame.args[1]
     if not raw or type(raw) ~= "string" then return 999999999 end
     if not rarity or type(rarity) ~= "string" then
        return 999999999
    end


     local trimmed = mw.text.trim(raw)
     -- Trim whitespace and strip leading ~
     if trimmed:sub(1, 1) == "~" then
    rarity = mw.text.trim(rarity)
         trimmed = trimmed:sub(2)
     if rarity:sub(1, 1) == "~" then
         rarity = rarity:sub(2)
     end
     end


     local lowered = string.lower(trimmed)
    -- Normalize lowercase
     local lowered = rarity:lower()


    -- Handle special values
     if lowered == "1" or lowered == "always" then
     if lowered == "1" or lowered == "always" then
         return 1
         return 1
Line 30: Line 38:
     end
     end


     local chance = lowered:match("^1/(%d+%.?%d*)$")
    -- Match and convert fractional chance like "1/2.5", "1/128"
     if chance then
     local num = lowered:match("^1/(%d+%.?%d*)$")
         return tonumber(chance) or 999999999
     if num then
         local n = tonumber(num)
        if n then
            return n
        end
     end
     end


    -- Unknown or badly formatted
     return 999999999
     return 999999999
end
end
Line 61: Line 74:
     if cleaned == "1" then
     if cleaned == "1" then
         return "Always"
         return "Always"
    end
    -- Format numbers like 1/10000 → 1/10,000
    local prefix, num = cleaned:match("^(1/)(%d+%.?%d*)$")
    if prefix and num then
        local withCommas = mw.language.getContentLanguage():formatNum(tonumber(num))
        return (hasTilde and "~" or "") .. prefix .. withCommas
     end
     end