Jump to content

Module:Convert/helper

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Johnuniq (talk | contribs) at 11:36, 2 August 2017 (prepare template parameters for use with {{convert}} per Template talk:Convert#input = value1 value2 ftin; based on code tested at Module:Biglist). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

-- This module provides some functions to prepare template parameters
-- for use with Template:Convert.
-- This module is not used by Template:Convert or Module:Convert.

local function strip_to_nil(text)
	-- If text is a non-empty string, return its trimmed content,
	-- otherwise return nothing (empty string or not a string).
	if type(text) == 'string' then
		return text:match('(%S.-)%s*$')
	end
end

-- For use by Template:NFL_predraft
local function number(frame)
	--[[ Preprocess a template parameter to translate a number to be used as
	input for {{convert}}.
	{{#invoke:convert/helper|number|12 3/8}} → 12+3/8
		Input				Output
		12					12
		12 3/8				12+3/8
		{{frac|12|3|8}}		12+3/8
		12{{frac|3|8}}		12+3/8
		12⅜					12+3/8
	Template:Fraction redirects to Template:Frac so either may be used in the input.
	]]
	local args = frame.args
	local text = strip_to_nil(args[1]) or ''
	if text == '' or tonumber(text) then
		return text  -- examples: '', '12', '12.3', '12.3e4', or negative
	end
	text = text:gsub(' ', ' '):gsub('  +', ' '):gsub('⁄', '/'):gsub('⁄', '/')
	local integer, numerator, denominator, rest
	-- Look for a fraction of form '12 3/8' or '3/8'.
	integer, numerator, denominator = text:match('^(%d+) (%d+)/(%d+)$')
	if integer then
		return integer .. '+' .. numerator .. '/' .. denominator
	end
	numerator, denominator = text:match('^(%d+)/(%d+)$')
	if numerator then
		return numerator .. '/' .. denominator
	end
	-- Look for an expanded fraction such as the result of {{frac|12|3|8}} or 12{{frac|3|8}} or {{frac|3|8}}.
	numerator, denominator = text:match('<sup>(%d+)</sup>/<sub>(%d+)</sub></span>')
	if numerator then
		integer = text:match('(%d+)<span class="visualhide">') or text:match('^(%d+)%s*<span')
		return (integer and (integer .. '+') or '') .. numerator .. '/' .. denominator
	end
	-- Look for a fraction of form '12¾' or '¾'.
	local fractions = {
		{ '½', '1/2' },
		{ '¼', '1/4' },
		{ '¾', '3/4' },
		{ '⅛', '1/8' },
		{ '⅜', '3/8' },
		{ '⅝', '5/8' },
		{ '⅞', '7/8' },
	}
	integer, rest = text:match('^(%d*)%s*(.*)')
	for _, frac in ipairs(fractions) do
		if rest == frac[1] then
			return (integer == '' and integer or (integer .. '+')) .. frac[2]
		end
	end
	return text
end

return {
	number = number,
}