Module:I18n/range

From Meta, a Wikimedia project coordination wiki
Module documentation
p={}
-- Constants
-- keep them identical to /data ones
START = 1 -- $5-10
END = 2 -- 5-10$
BEFORE_BOTH = 3 -- $5-$10
AFTER_BOTH = 4 -- 5$-10$
AFTER_FIRST = 5 -- 5$-10
BEFORE_FIRST = START
BEFORE_SECOND = 6 -- 5-$10
AFTER_SECOND = END

--[[
Creates a range formatted according to language data provided by /data subpage.

Arguments:
- from: (number) lower element of the range
- to: (number) higher element of the range
- unit: (string) unit for these numbers
- cur: (bool) whether unit is a currency
- lang: (string) language code in which to get formatting data (defaults to {{PAGELANGUAGE}})
]]

p.main = function (frame)
	args = frame.args
	rendering = ""
	
	langCode = args["lang"] or frame:preprocess("{{PAGELANGUAGE}}")
	lang = mw.language.new(langCode)
	
	from = lang:formatNum(tonumber(args["from"] or ""))
	to = lang:formatNum(tonumber(args["to"] or ""))
	unit = args["unit"] or ""
	
	isCurrency = args["cur"] and args["cur"] ~= "" or false
	
	i18nData = mw.loadData("Module:I18n/range/data")
	localData = i18nData[langCode] or {}
	defaultData = i18nData["en"]
	
	rangeSeparator = localData["range_sep"] or defaultData["range_sep"]
	if isCurrency then
		unitSeparator = localData["cur_sep"] or defaultData["cur_sep"]
		unitLocation = localData["cur_loc"] or defaultData["cur_loc"]
	else
		unitSeparator = localData["unit_sep"] or defaultData["unit_sep"]
		unitLocation = localData["unit_loc"] or defaultData["unit_loc"]
	end
	
	if unit == "" then
		unitSeparator = ""
	end
	
	if unitLocation == START then
		rendering = unit .. unitSeparator .. from .. rangeSeparator .. to
	elseif unitLocation == END then
		rendering = from .. rangeSeparator .. to .. unitSeparator .. unit
	elseif unitLocation == BEFORE_BOTH then
		rendering = unit .. unitSeparator .. from .. rangeSeparator .. unit .. unitSeparator .. to
	elseif unitLocation == AFTER_BOTH then
		rendering = from .. unitSeparator .. unit .. rangeSeparator .. to .. unitSeparator .. unit
	elseif unitLocation == AFTER_FIRST then
		rendering = from .. unitSeparator .. unit .. rangeSeparator .. to
	elseif unitLocation == BEFORE_SECOND then
		rendering = from .. rangeSeparator .. unit .. unitSeparator .. to
	end
	
	return rendering
end

return p