From WikiChip
Module:ordinal
Revision as of 03:50, 30 December 2019 by David (talk | contribs) (Created page with "local p = {} function p.ordinal(frame) local args = frame.args if args[1] == nil then args = frame:getParent().args end if args[1] == nil then args[...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

local p = {}

function p.ordinal(frame)
	local args = frame.args
    if args[1] == nil then
        args = frame:getParent().args
    end
    if args[1] == nil then
    	args[1] = "{{{1}}}"
    end
    return p._ordinal(args[1], (args[2] == 'd'), args.sup)
end

function p._ordinal(n, d, sup)
	local x = tonumber(mw.ustring.match(n, "(%d*)%W*$"))
	local suffix = "th"
	-- If tonumber(n) worked:
	if x then
		local mod10 = math.abs(x) % 10
		local mod100 = math.abs(x) % 100
		if     mod10 == 1 and mod100 ~= 11 then
			suffix = "st"
		elseif mod10 == 2 and mod100 ~= 12 then
			if d then suffix = "d" else suffix = "nd" end
		elseif mod10 == 3 and mod100 ~= 13 then
			if d then suffix = "d" else suffix = "rd" end
		end
	end
	if sup then
		suffix = "<sup>" .. suffix .. "</sup>"
	end
	return n .. suffix
end

return p